Multiple variable let in Kotlin

后端 未结 12 1157
失恋的感觉
失恋的感觉 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:39

    one more idea based on the answer by @yole

    fun  Pair.toLet(body: (List<*>) -> R): R? {
        val one = first
        val two = second
        if (one == null || two == null)
            return null
        return if (one is Pair<*, *>) {
            one.toLet { a ->
                body(listOf(a, listOf(two)).flatten())
            }
        } else {
            body(listOf(one, two))
        }
    }
    

    so you can do the following

    (1 to 6 to "a" to 4.5).toLet { (a, b, c, d) ->
        // Rest of code
    }
    
    

提交回复
热议问题