Kotlin call function only if all arguments are not null

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

    NO! is the answer to your question(as far as I know)

    Your best bet(assuming the function is not exposed) is what you said.

    a?.let { b?.let { test(a, b) } }
    

    If the function is exposed, and might be called without these checks, then you need to put the checks inside your function.

    fun test(a: Int?, b: Int?) {
        if (listOf(a, b).filterNotNull().size < 2) return
    
        println("Function was called")
    }
    

提交回复
热议问题