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.