Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pattern match optionals in Kotlin?

Is it possible to write something like this, or do we have to revert back to manual null checking in Kotlin?

val meaningOfLife : String? = null

when meaningOfLife {
    exists -> println(meaningOfLife)
    else   -> println("There's no meaning")
}
like image 369
TomTom Avatar asked Jun 03 '16 09:06

TomTom


People also ask

Does kotlin support pattern matching?

The kotlin language has many default classes, methods & variables for implementing the application. Based on that pattern matching is one of the regular expression types using these regular expression objects the instances are called using the default methods implemented with the kotlin.

How does kotlin handle optional?

When mapping an Optional in Java, sometimes you have to unwrap another Optional . To do this, you use flatMap() instead of map() . With Kotlin's null system, the value is either present, or null , so there's nothing to unwrap. This means that Kotlin's equivalent for flatMap() and map() are similar.

How do I print a variable type in Kotlin?

Kotlin Print Functions To print a variable inside the print statement, we need to use the dollar symbol($) followed by the var/val name inside a double quoted string literal.

How do you check the object type in Kotlin?

Basically, the is operator is used to check the type of the object in Kotlin, and “!is” is the negation of the “is” operator. Kotlin compiler tracks immutable values and safely casts them wherever needed. This is how smart casts work; “is” is a safe cast operator, whereas an unsafe cast operator is the as operator.


2 Answers

One of possible ways is to match null first so that in else branch the String? is implicitly converted to String:

val meaningOfLife: String? = null

when (meaningOfLife) {
    null -> println("There's no meaning")
    else -> println(meaningOfLife.toUpperCase()) //non-nullable here
}

This is a special case of a smart cast performed by the compiler.

Similar effect can be achieved with is String and else branches -- is String-check is true when the value is not null.

For more idioms regarding null-safety please see this answer.

like image 113
hotkey Avatar answered Oct 25 '22 18:10

hotkey


You can accomplish that as follows:

val meaningOfLife: String? = null

when (meaningOfLife) {
  is String -> println(meaningOfLife)
  else -> println("There's no meaning")
}
like image 34
EPadronU Avatar answered Oct 25 '22 18:10

EPadronU