Kotlin call function only if all arguments are not null

前端 未结 5 1105
太阳男子
太阳男子 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:27

    If you don't want callers to have to do these checks themselves, you could perform null checks in an intermediary function, and then call into the real implementation when they passed:

    fun test(a: Int?, b: Int?) {
        a ?: return
        b ?: return
        realTest(a, b)
    }
    
    private fun realTest(a: Int, b: Int) {
        // use params
    }
    

    Edit: here's an implementation of the function @Alexey Romanov has proposed below:

    inline fun  ifAllNonNull(p1: T1?, p2: T2?, function: (T1, T2) -> R): R? {
        p1 ?: return null
        p2 ?: return null
        return function(p1, p2)
    }
    
    fun test(a: Int, b: Int) {
        println("$a, $b")
    }
    
    val a: Int? = 10
    val b: Int? = 5
    ifAllNonNull(a, b, ::test)
    

    Of course you'd need to implement the ifAllNonNull function for 2, 3, etc parameters if you have other functions where you need its functionality.

提交回复
热议问题