Multiple variable let in Kotlin

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

    I actually prefer to solve it using the following helper functions:

    fun  T(tuple: Pair): Pair? =
        if(tuple.first == null || tuple.second == null) null
        else Pair(tuple.first!!, tuple.second!!)
    
    fun  T(tuple: Triple): Triple? =
        if(tuple.first == null || tuple.second == null || tuple.third == null) null
        else Triple(tuple.first!!, tuple.second!!, tuple.third!!)
    
    
    fun  T(first: A?, second: B?): Pair? =
        if(first == null || second == null) null
        else Pair(first, second)
    
    fun  T(first: A?, second: B?, third: C?): Triple? =
            if(first == null || second == null || third == null) null
            else Triple(first, second, third)
    

    And here's how you should use them:

    val a: A? = someValue
    val b: B? = someOtherValue
    T(a, b)?.let { (a, b) ->
      // Shadowed a and b are of type a: A and b: B
      val c: C? = anotherValue
      T(a, b, c)
    }?.let { (a, b, c) ->
      // Shadowed a, b and c are of type a: A, b: B and c: C
      .
      .
      .
    }
    

提交回复
热议问题