![]() ![]() The type of s?.length is Int?, so after calling s?.length, the compiler checks that Int? is used safely. However, a call to s?.length will return s.length if s is not null otherwise it will return null. If s is nullable, and if the compiler can't verify that s is not null at the point where s is dereferenced, then a call to s.length will be flagged as a compile-time error. Println(s1.length) // will never throw NPE Var s2: String? = "abc" // s2 is nullable Var s1: String = "abc" // s1 is not nullable So, for example, in Kotlin, a variable of type String can never be null, but a variable of type String? (note ? suffix) can. The Kotlin type system distinguishes between references that can hold null values (nullable references) and those that can't, and the compiler will verify consistent usage of variables of each type. More than any other language I have used, Kotlin greatly reduces occurrences of the dreaded NullPointerException. ![]() One of the major design goals of Kotlin was to eliminate, or at least greatly reduce problems associated with null references.
0 Comments
Leave a Reply. |