Multiple variable let in Kotlin

后端 未结 12 1173
失恋的感觉
失恋的感觉 2020-11-30 18:48

Is there any way to chain multiple lets for multiple nullable variables in kotlin?

fun example(first: String?, second: String?) {
    first?.let {
        se         


        
12条回答
  •  天涯浪人
    2020-11-30 19:52

    I have upgraded the expected answer a bit:

    inline fun  ifLet(vararg elements: T?, closure: (List) -> R): R? {
        return if (elements.all { it != null }) {
            closure(elements.filterNotNull())
        } else null
    }
    

    this makes this possible:

    iflet("first", "sconed") {
        // do somehing
    } ?: run {
        // do this if one of the params are null
    }
    

提交回复
热议问题