我很清楚Kotlin的零安全性.我知道在类型之后(例如:Int?)可用于将变量或值声明为可空.我也知道!!运算符用于返回非空值或抛出NPE.

通常,带有""的类型之后,它将可为空,并且没有"?"是非空的.但当我判断一些变量时,我看到了如下情况:

var myVariable:Int!

It happens when you use java code from kotlin code.

//java code
public class Foo {
    public Integer calcNumber()
    {
        return null;
    }
}

If I use the function Foo.calcNumber()

//kotlin code
val meh = Foo().calcNumber()
print(meh)

值meh被判断为Int!,不是Int也不是Int?.显然,这里的值meh可以为null,但"IDE"无法正确地"检测到".

As

var a: Int! = 10

is invalid, my question is: What does exactly mean types with "!"?

推荐答案

The Type! notation is called a Platform Type and is critical for Interoperability with the weaker-typed Java; it means "the null-ability is unknown" and it allows for relaxed null-ability enforcement. I found the examples in the linked question underwhelming.. although all the information is there.

下面的程序是accepted as type-safe,因为Kotlin允许x/Int的类型!要用作"Int或Int"的表达式.

var x = JavaIntegerList.get(0); // Int! type inferred by Kotlin
var y: Int? = x;
var z: Int = x;

However, the assignment to z (Int) will fail at run-time if x evaluates to null. (For class implementation types, the NPE may delayed to usage: basically, Kotlin chooses to 'get out of the way'.)

It's thus designed for cases when it is known that the value "cannot" be null in a valid program, although the value comes from Java outside of the Kotlin type system. Highly applicable to int-box-Integer in Java, although it is valid for any class type / value coming in from Java. If the Java code can return null, it is safest to put the value into a Type? immediately and then correctly deal with the null-ability.

将其与具有类似运行时失败语义的Java代码进行比较:

// Java
Integer x = JavaIntegerList.get(0);
Integer y = x;  // "No OP" - all class types in Java are null-able
int z = (int)x; // kaboom *at run-time* if x is null!

While simple to show with ints, as in this example, this issue is not strictly related to Java's int/Integer types. The document linked above shows a case of String! being implicitly used, giving the example that item.substring(1), where item is a String! is allowed/type-safe but will fail at run-time if item evaluates to null.

Kotlin相关问答推荐

如何在Android应用判断上运行多个查询

合并状态流

使用 Kotlin 的 Springboot 中缺少 ResponseEntity 正文属性

如何将光标从一个文本字段传递到 Jetpack Compose 中的其他文本字段?

使用启动或使用 coroutineScope 启动协程之间的区别

为什么这个 Kotlin 代码不起作用? (如果 str[index] 在列表中,则打印)

在 Compose 中使用 Text() 时如何获取文本的大小?

如何连接两个 kotlin 流?

如何在kotlin中使用协程每秒调用一个函数

在协程中等待侦听器内的数据

Kotlin DataBinding 将静态函数传递到布局 xml

如何在 Kotlin 中传递有界通配符类型参数?

Kotlin协程处理错误和实现

Kotlin中具有多个参数的绑定适配器

在 Kotlin 函数上使用 Mokito anyObject() 时,指定为非 null 的参数为 null

有没有办法在Kotlin中设置一个私有常量

如何在不绑定ViewModel(MVVM)中的UI的情况下使用android导航?

比较Kotlin的NaN

从另一个列表创建一个列表

使用 Kotlin 按字母对数组进行排序