I wonder what is the best way to handle such scenario
class Person(var name:String? = null, var age:Int? = null){
fun test(){
if(name != null && age != null)
doSth(name, age) //smart cast imposible
}
fun doSth (someValue:String, someValue2:Int){
}
}
What is the simplest way to call doSth method and making sure that name and age are nt null?
I am looking for something simple as with one variable scenario where I would simply use let
name?.let{ doSth(it) }
You can nest let
as much as you like so:
fun test(){
name?.let { name ->
age?.let { age ->
doSth(name, age) //smart cast imposible
}
}
}
Another approach, that might be easier to follow, is to use local variables:
fun test(){
val name = name
val age = age
if(name != null && age != null){
doSth(name, age)
}
}
Last but not least, consider changing Person
to be immutable like so:
data class Person(val name:String? = null, val age:Int? = null){
fun test(){
if(name != null && age != null){
doSth(name, age)
}
}
...
}
For the cast to be possible you have to make a local copy of the value somehow. In Kotlin this is best done explicitly:
val name = name
val age = age
if(name != null && age != null){
doSth(name, age)
}
The let
function hides this behind an abstraction layer, which is not the best IMHO.
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