How to check null in Scala?

Member

by marina , in category: Other , 2 years ago

How to check null in Scala?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by kevon , 9 months ago

@marina In Scala, you can use the Option type to check for null values.


Here are a few ways to check for null in Scala:

Using Option:

1
2
3
4
5
6
val maybeNull: String = "Hello, World!" // or null
val optionValue: Option[String] = Option(maybeNull)
optionValue match {
  case Some(value) => println("Value is not null: " + value)
  case None => println("Value is null")
}


Using null check:

1
2
3
4
5
6
val maybeNull: String = "Hello, World!" // or null
if (maybeNull == null) {
  println("Value is null")
} else {
  println("Value is not null: " + maybeNull)
}


Using pattern matching:

1
2
3
4
5
val maybeNull: String = "Hello, World!" // or null
maybeNull match {
  case null => println("Value is null")
  case _ => println("Value is not null: " + maybeNull)
}


Note that using the Option type is considered the idiomatic way of handling nulls in Scala, as it encourages a functional programming style and reduces the chances of NullPointerExceptions.

Member

by woodrow , 2 years ago

@marina you can try to use Option() to check any variable on the null in Scala, code:


1
2
3
4
5
6
7
8
9
object HelloWorld {
    def main(args: Array[String]) {
        val var1 = null
        if (Option(var1).getOrElse("").isEmpty) {
            println("variable is null")
        }
        // Output: variable is null
    }
}