[英]Change nullability of overridden function's parameter in kotlin
I am implementing an interface of a third party library(java). 我正在实现第三方库(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)
? 如果基础库调用
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. 来自Java的类型是平台类型(在这种情况下,此参数的类型为
String!
如果Java中未注释该参数,则由您决定是否可以具有null
值,并且必须标记如果将其标记为不可为空,但是Java代码将其传递为null
,则在运行时会收到异常-Kotlin会生成对此类参数的检查,您可以通过反编译来查看生成的字节码。
Also see the official docs about null safety and platform types for more detail. 另请参阅有关空安全性和平台类型的官方文档,以获取更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.