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")
}
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.
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.
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.
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.
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.
You can accomplish that as follows:
val meaningOfLife: String? = null
when (meaningOfLife) {
is String -> println(meaningOfLife)
else -> println("There's no meaning")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With