![]() Here you are saying to the compiler, "Look, I am confident that s is not null at this point, and I assume responsibility if it is. In Kotlin, you can use the !! operator to tell the compiler to ignore checks for null safety. With the Elvis operator, the code in Listing 7 can be written more simply as shown in Listing 8. ![]() If the value on the left is null, then the value on the right of the operator is used. If the value on the left of the operator is not null, then that value is used as the result of applying the operator. The left side of the operator is an expression that can be null. Kotlin has a "null coalescing" operator ( ?:), which is more popularly known as the "Elvis" operator, because if you turn your head slightly it resembles Elvis Presley's pompadour. Val len : Int = if (s != null) s.length else -1 If it isn't, we use that property, but if it is, we want to use a different value in our code. The Elvis operatorįrequently in programming we want to use a specific property of a nullable variable, so we check first to ensure that it isn't null. Since the function println can handle null values, a call to println(s?.length) is safe and will print either the length of the string or the word "null". 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. |