Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to handle such scenario where "smart cast is imposible"

Tags:

kotlin

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) } 
like image 426
Igor Avatar asked Aug 31 '16 09:08

Igor


2 Answers

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)
        }
    }
    ...
}
like image 92
miensol Avatar answered Nov 06 '22 15:11

miensol


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.

like image 3
voddan Avatar answered Nov 06 '22 14:11

voddan