A trick about non-nullable l type in kotln

本文探讨了Kotlin中非空类型的一个鲜为人知的特性:尽管非空类型理论上不能被赋空值,但通过Java代码可以绕过这一限制,导致运行时NullPointerException。文章提供了示例代码,并建议在从Java代码赋值给非空类型变量前进行空值检查。

Note: 原创,非翻译。

What is “A trick about non-nullable type in Kotlin?”
The trick is that: "non-nullable type isn’t always being non-nullable at complie time."

As well known, a non-nullable type can’t be assigned with a null at compile time. If you force to run, your app will be failed at compile time. But Is there a way to around this constraint? Yes, there is.

Because you can compile Kotlin code with Java and Java doesn’t have a platform type called non-nullable. So that, you can pass a non-nullable type var as paramter into a Java method in which assign a null to it and return to the non-nullable var in Kotlin.

Having said that, your app still will throw an exception eventually but that will happen at runtime not at compile time. If so, the non-nullable type will lose it’s function(It’s better to detect a NullPointerExecption at compile time). Now, Let’s see how to concrete it:

        // Define a non-nullable type var.
        var test: String = ""
        
        // Assign a null to a non-nullable type var from Java code.
        test = NotificationUtil.test(test)
        
        public class NotificationUtil {
        
        public static String test(String test) {
           test = null;
           return test;
    }
}

What we should do for it ? To avoid a NullPointerExecption thrown at runtime?

  1. Be careful when you assign a value to a non-nullable type var from Java code.
  2. It’s better to check value whether it’s null from java code, before assigning it to a non-nullable type var.
  3. The less java code you compiled with Kotlin, The less problems you will encounter.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值