Best way to handle such scenario where “smart cast is imposible”

前端 未结 7 807
鱼传尺愫
鱼传尺愫 2020-12-20 17:33

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 &am         


        
7条回答
  •  不思量自难忘°
    2020-12-20 18:37

    If you want to take it a little "extreme" you could define an extension function on Pair that hides the logic for you:

    fun Pair.test(block: (String, Int) -> Unit) {
        if(first != null && second != null) {
             block(first, second)
        }
    }
    

    then, calling it will be a little more concise

    (name to age).test { n, a ->
       println("name: $n age: $a")
    }
    

    However, it won't really help you (since you could as well define this as a function inside the Person class itself), unless you need this kind of functionality really often throughout the whole project. Like I said, it seems overkill.

    edit you could actually make it (a little) more useful, by going fully generic:

    fun  Pair.ifBothNotNull(block: (T, R) -> Unit) {
        if(first != null && second != null){
             block(first, second)
        }
    }
    

提交回复
热议问题