简体   繁体   中英

How can I prevent from passing null of a different type to a function

I was surprised that this code compiled in Kotlin.

fun foo(key: String, value: Int?) {
    if (value == null) {
        bar(value)
    }
}

fun bar(key: String?) {
}

As you can see foo passes value of type Int? to bar as String? . I guess this compiles because value must be null in this context, but apparently, bar(value) in foo was a typo of bar(key) .

Are there any compiler options to make this an error or a warning, or are there common practices to prevent this error? I'd also like to know in which use cases this behavior is useful.

I'm using Kotlin version 1.3.50-release-112 (JRE 1.8.0_152-b16) .

Note that this code doesn't compile (as I expected).

fun foo(key: String, value: Int?) {
    bar(value)
}

fun bar(key: String?) {
}

with this error.

k2.kt:2:9: error: type mismatch: inferred type is Int? but String? was expected
    bar(value)

are there common practices to prevent this error?

Yes - avoid using null and/or accepting nullable parameters.

The method fun bar(key: String?) is actually two different functions - one with and one without input. The implementation could look like:

fun foo(key: String, value: Int?) {
    if (value == null) {
        barEmpty()
    } else {
        /*Something else*/
    }
}

fun bar(key: String) {}

fun barEmpty() {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM