Kotlin and idiomatic way to write, 'if not null, else…' based around mutable value

前端 未结 5 1779
谎友^
谎友^ 2021-02-01 12:53

Suppose we have this code:

class QuickExample {

    fun function(argument: SomeOtherClass) {
        if (argument.mutableProperty != null ) {
            doSome         


        
5条回答
  •  不知归路
    2021-02-01 13:47

    add custom inline function as below:

    inline fun  T?.whenNull(block: T?.() -> Unit): T? {
        if (this == null) block()
        return this@whenNull
    }
    
    inline fun  T?.whenNonNull(block: T.() -> Unit): T? {
        this?.block()
        return this@whenNonNull
    }
    

    then you can write code like this:

    var nullableVariable :Any? = null
    nullableVariable.whenNonNull {
        doSomething(nullableVariable)
    }.whenNull {
        doOtherThing()
    }
    

提交回复
热议问题