简体   繁体   中英

Change nullability of overridden function's parameter in kotlin

I am implementing an interface of a third party library(java). I am overriding a function with the following signature:

override fun onCallback(name: String?) {

}

I can change to the following without the compiler complaining:

override fun onCallback(name: String) {

}

What is the effect of this? What happens if the underlying library calls onCallback(null) ?

Types coming from Java are platform types (in this case, this parameter has a type of String! . If the parameter is not annotated in Java, it's up to you to decide whether it can ever have a null value, and you have to mark the type of the parameter in Kotlin accordingly. If you mark it as non-nullable, but Java code passes null to it, you'll get an exception at runtime - Kotlin generates checks for parameters like this, which you can look at by decompiling the generated bytecode.

Also see the official docs about null safety and platform types for more detail.

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