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

前端 未结 7 773
鱼传尺愫
鱼传尺愫 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<String?,Int?> that hides the logic for you:

    fun Pair<String?,Int?>.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 <T,R> Pair<T?,R?>.ifBothNotNull(block: (T, R) -> Unit) {
        if(first != null && second != null){
             block(first, second)
        }
    }
    
    0 讨论(0)
提交回复
热议问题