![]() ![]() There is also the cutely named Elvis operator ?: which will replace a null value with something that is non-null. Note: the block of code is a lambda function. The block of code in the curly brackets is only executed if a is non-null. If you only want to perform an operation if something is non-null you can use the let method: a?.let In this case we use the plus infix function rather than an operator so that we can use the safe call operator. That is, the integer a is a full object with methods and properties. There are a few small things to notice about this example – by type inference b is a nullable type: var b:Int? = a?.plus(1)Īnd nullable simple types are "boxed". Here, if a isn't null then b is set to 2, but if a is null then b is set to null. This compiles and you can be sure that a isn't null when the addition is performed.Īlternatively, if you are accessing a property then you can use the safe call operator ?. To use a nullable variable you can test for null using an if statement: var a: Int? = 1 Generates a compiler error because you are adding one to a without checking that it isn't null. Works without any problems as a can never be null as it is a non-nullable, but: var a:Int? = 1 To avoid accidentally using a null reference the compiler will throw an error if you try to use a nullable without first checking that it is non-null. Works without a compiler error or warning. ![]() Now myVariable can be set to null, i.e.: myVariable = null If you need a nullable reference then you have to explicitly declare it using ? as in: var myVariable: sometype? = something This often occurs if you are trying to use a Java function which, of course, doesn’t support non-nullable types. For example, if a function could return a null, you cannot assign it to a non-nullable. The compiler tracks operations that could generate a null, and flags any operation that could possibly set a non-nullable variable to null. ![]() If you declare a variable in the usual way you get a non-nullable: var myVariable: sometype = somethingĪnd you cannot set the variable to null as: myVariable = null References can be either non-nullable or nullable. ![]() One of the most important features of Kotlin is that it eliminates the null reference error and you can’t meet null safety early enough. ![]()
0 Comments
Leave a Reply. |