Kotlin call function only if all arguments are not null

前端 未结 5 1143
太阳男子
太阳男子 2021-01-08 01:05

Is there a way in kotlin to prevent function call if all (or some) arguments are null? For example Having function:

fun test(a: Int, b: Int) { /* function bo         


        
5条回答
  •  无人及你
    2021-01-08 01:39

    Let for Tuples (Pair & Triple)

    I think the spirit of the OP was syntax, so my answer focuses on providing "let" for tuple types:

    Example use:

    fun main() {
        val p1: Int? = 10 // or null
        val p2: Int? = 20 // or null
        val p3: Int? = 30 // or null
    
        val example1 = (p1 to p2).let(::testDouble)
        val example2 = (p1 to p2).let { a, b -> a * b }
    
        val example3 = (p1 to p2 to p3).let(::testTriple)
        val example4 = (p1 to p2 to p3).let { a, b, c -> a * b * c }
    }
    
    fun testDouble(a: Int, b: Int): Int {
        return a + b
    }
    
    fun testTriple(a: Int, b: Int, c: Int): Int {
        return a + b + c
    }
    

    Extension Funs:

    // Define let for Pair & Triple
    fun  Pair.let(f: (P1, P2) -> R): R? {
        return f(first ?: return null, second ?: return null)
    }
    
    fun  Triple.let(f: (P1, P2, P3) -> R): R? {
        return f(first ?: return null, second ?: return null, third ?: return null)
    }
    
    // Cute "to" syntax for Triple
    infix fun  Pair.to(third: P3?): Triple {
        return Triple(first, second, third)
    }
    

    You can replace "to" with another word (see Triple extension as a guide), and you could extend to larger tuples (but Kotlin only provides 2 out-of-the-box & sadly I don't think it can be generic).

提交回复
热议问题