Change nullability of overridden function's pa

2019-07-14 09:35发布

问题:

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)?

回答1:

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.



标签: kotlin