更改Kotlin中覆盖函数的参数的可空性 [英] Change nullability of overridden function's parameter in kotlin

查看:47
本文介绍了更改Kotlin中覆盖函数的参数的可空性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现第三方库(java)的接口.我使用以下签名覆盖了一个函数:

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

}

这有什么作用?如果基础库调用onCallback(null)会发生什么?

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

推荐答案

来自Java的类型是平台类型(在这种情况下,此参数的类型为String!.如果在Java中未注释该参数,则表明已启动决定它是否可以具有null值,并且必须在Kotlin中相应地标记参数的类型.如果将其标记为不可为空,但是Java代码将null传递给它,则会在运行时遇到异常-Kotlin会生成对此类参数的检查,您可以通过反编译所生成的字节码来查看这些参数.

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.

另请参阅有关 null的官方文档安全和平台类型以获取更多详细信息.

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

这篇关于更改Kotlin中覆盖函数的参数的可空性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆