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

前端 未结 5 1672
谎友^
谎友^ 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:33

    You could also do something like this:

    class If(val any: T?, private val i: (T) -> Unit) {
        infix fun Else(e: () -> Unit) {
            if (any == null) e()
            else i(any)
        }
    }
    

    You can then use it like this:

    If(nullableString) {
       //Use string
    } Else {
    
    }
    

提交回复
热议问题