Kotlin call function only if all arguments are not null

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

    If you try assigning null to any of the two Int variables you will find that this doesn`t work. See the compile errors in the comments.

    fun test(a: Int, b: Int) { /* function body here */ }
    
    fun main(){
        test(null, 0) //Null can not be value of non-null type Int
        val b : Int? = null
        test(0, b) // Type mismatch. Required: Int - Found: Int?
    }
    

    The example shows that in a pure Kotlin world test(a: Int, b: Int) cannot be called with null or even Int? arguments. If you put Java in the mix I doubt there is a safe solution without null checks, because you can call test(Int, Int) with type Integer from the Java side, which allows null. The Java "equivalent" to Int would be @NotNull Integer (which is not really null-safe).

提交回复
热议问题