Horje
How to check String is null in Scala?

In this article, we will learn how to check if a string is null in Scala. In Scala, you can check if a string is null using the following methods:

1. Using the == operator:

Scala
object Main {
    def main(args: Array[String]) {
        val str: String = null
        if (str == null) {
          println("String is null")
        } else {
          println("String is not null")
        }
    }
}

Output:

String is null

The eq method is a null-safe way of comparing objects in Scala. It returns true if both operands are null, or if the operands point to the same object instance.

Scala
object Main {
    def main(args: Array[String]) {
        val str: String = null
        if (str eq null) {
          println("String is null")
        } else {
          println("String is not null")
        }
    }
}

Output:

String is null

3. Using Pattern Matching:

Scala
object Main {
    def main(args: Array[String]) {
        val str: String = null
        str match {
          case null => println("String is null")
          case _    => println("String is not null")
        }
    }
}

Output:

String is null

It’s generally recommended to use the eq method or pattern matching for checking null references, as they provide a more concise way of handling null values in Scala.




Reffered: https://www.geeksforgeeks.org


Scala

Related
How to connect MySQL database using Scala? How to connect MySQL database using Scala?
How to Merge Two Lists and Remove Duplicates in Scala? How to Merge Two Lists and Remove Duplicates in Scala?
How to Escape Double Quotes in Scala? How to Escape Double Quotes in Scala?
Scala - Expression that Can't be Reduced to a Value Scala - Expression that Can't be Reduced to a Value
Domain-Specific Languages in Scala Domain-Specific Languages in Scala

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12