Multiple variable let in Kotlin

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

    For any amount of values to be checked you can use this:

        fun checkNulls(vararg elements: Any?, block: (Array<*>) -> Unit) {
            elements.forEach { if (it == null) return }
            block(elements.requireNoNulls())
        }
    

    And it will be used like this:

        val dada: String? = null
        val dede = "1"
    
        checkNulls(dada, dede) { strings ->
    
        }
    

    the elements sent to the block are using the wildcard, you need to check the types if you want to access the values, if you need to use just one type you could mutate this to generics

提交回复
热议问题