The documentation for Kotlin is now located on the new site. This page is kept for historical reasons

Nullable types and Non-null types

One of the most common pitfalls in Java programming is accessing a member of a null reference, that results in a NullPointerException, because virtually any reference in a Java program can hold null. It happens so often that we have a casual abbreviation for it: NPE. Also have a look at this talk: "The Billion Dollar Mistake".

Kotlin's type system is aimed to eliminate NullPointerException's from our code. The only possible causes of NPE's may be

Someone had explicitly thrown is (throw NullPointerException())

Someone called external Java code that caused it

There's data inconsistency w.r.t initialization (an uninitialized this available in a constructor is used somewhere)

In Kotlin the type system distinguishes between references that can hold null (nullable references) and those that can not (non-null references). For example, a regular variable of type String can not hold null:

vara:String="abc"

a=

null

// compilation error

To allow nulls, one declares a variable as nullable string, written String?:

varb:String?="abc"

b=null// ok

Now, if you call a method on a, it's guaranteed not to cause an NPE, so you can safely say

vall=a.length()

But if you want to call the same method on b, that would not be safe, and the compiler reports an error:

vall=b

.

length()// error: variable 'b' can be null

But we still need to call that method, right? There are a few ways of doing that.

Checking for null in conditions

First, you can explicitly check if bisnull, and handle the two options separately:

vall=if(b!=null)b.length()else-1

The compiler tracks the information about the check you performed, and allows the call to length() inside the if. More complex conditions are supported as well:

if(b!=null&&b.length()>0)

print("String of length ${b.length()}")

else

print("Empty string")

Note that this only works where b is immutable (i.e. a local val or a member val which has a backing field and is not overridable), because otherwise it might happen that b changes to nullafter the check.

Safe calls

Your second option is the safe call operator, written ?.:

b?.length()

This returns b.length() if b is not null, and null otherwise. The type of this expression is Int?.

Safe calls are useful in chains. For example, if Bob, an Employee, may be assigned to a Department (or not), that in turn may have another Employee as a department head, then to obtain the name of Bob's department head, if any), we write the following:

bob?.department?.head?.name

Such a chain returns null if any of the properties in it is null.

Elvis operator

When we have a nullable reference r, we can say "if r is not null, use it, otherwise use some non-null value x":

vall:Int=if(b!=null)b.length()else-1

Along with the complete if expression, this can be expressed with the Elvis operator, written ?::

vall=b?.length()?:-1

If the expression to the left of ?: is not null, the elvis operator returns it, otherwise it returns the expression to the right. Note that the right-hand side expression is evaluated only if the left-hand side is null.

The !! operator

The third option is for NPE-lovers. One can write b!!, and this will return a non-null value of b (e.g., a String in our example) or throw an NPE if b is null:

vall=b!!.length()

Thus, if you want an NPE, you can have it, but you have to ask for it explicitly, and it does not appear out of the blue.

By the way, !! is added for conciseness, and formerly was emulated by an extension function from the standard library, defined as follows:

inlinefun<T:Any>T?.sure():T=

if(this==null)

throwNullPointerException()

else

this

Safe casts

Regular casts may result into a ClassCastException if the object is not of the target type. Another option is to use safe casts that return null is the attempt was not successful:

Best practices related to this feature

Similar features in other languages

In Java, one can use annotations on methods and parameters (or on types, when JSR-308 is accepted), these annotations can be used by external tools to verify null-safety. For example, one can use the @NotNull annotation supported by IntelliJ IDEA.

Scala promotes using the Option type to control absent values. This introduces run-time overhead because values are wrapped into objects of type Option, and the syntax is a little verbose.

C# has Nullable types (hhttp://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.80).aspx) that boil down to wrapping references into value types allocated on the stack, and there's no actual static checks that would prohibit calling methods on a null reference.

What's next

58 Comments

Anonymous

Any plans on adding Design By Contract type features other than null checking. It is quite cumbersome in most languages to check for preconditions (postconditions, invariants) and then copy the precondition text into the function doc and then finally write a unit test to exercise the precondition check.

For example:

/** does it.
@param i cannot be < 0 or > 100.
@return will never be less than zero
*/
int doIt(Int i)

Instead I'd like to be able to write (maybe this isn't the best syntax but you get the idea). The conditions would be part of the method signature and therefore they don't have to be doc'd or tested (unless you want to make sure they don't change).

/** does it. */
int (< 0) doIt(int (< 0 || > 100) i)

Unknown macro: { ...}

aside from reducing boilerplate docs, tests, etc. It would be cool if the compiler could check these constraints at compile time. I'm thinking something similar to what microsoft is doing with specsharp & code contracts

We do the same level of assuredness of nonnullability as Java does for final fields being actually final. In some obscured initialization logic where reference to this is escaped before initialization is complete one may see final field being null even though it definitely initialized to some nonnull value.

Yes and I don't think that this counter-intuitive when you know about existence of such operator ("double negation is assertion"). And double negation is not something that you use commonly, in fact, the only use could be in case of some weird operator overloading.

Speaking of operator overloading... maybe it is possible to implement such feature with current syntax? Though it will require dangerous overriding of Any?.not, creating some intermediate value, and will allow compile-time !x expression for any type.

the other suggestions look like punctuation soup. if something had to be done, I would just let `if (value)` mean `if (value != null)`. i know, this is something that horrible scripting languages do, but I don't think it's too bad. booleans are typically prefixed with "is," and nullable types shouldn't occur too often in code.

Any likelihood to special case idioms like this from the JDK? Although one could technically set out & err to null, it would be obscure. Were I reviewing "System.setOut(null)" in a fellow's code, I'd call them out on it.

Thank you for clarification!
Does it mean that it's not possible to use ` ?. ` operator for accessing class property?
As I understand, correct implementation must involve copying the value from property to synthetic local variable:

vallen=this.someNullableString?.length()

// must be implemented equally to:

val_tmp=this.someNullableString// someNullableString can be safely set to null from another thread now

It is a pity since there are many use cases where we know we are in a single threaded environment and there is no chance a var may become null. I am looking forward to the analyzer improvement, but I cannot imagine how this could be done.

Are nullable types somehow retained in bytecode? Is there a way to introspect the nullability of a property using reflection? Maybe the compiler could implicitly add some specific annotation to such properties? This could be useful in ORMs which could emit NOT_NULL statements in DDL automatically.

I have yet another question about null-safe design approach. Sorry if you've already covered it elsewhere.

In Scala, Options (thus nullable types) are treated pretty much like collections: for non-null value we have a one-element collection; or we get Nil otherwise. This approach brings a couple of techniques I currently can't imagine my life without:

using monadic functions on nullable types, as you normally do with collections:

returning values in flatMap, when working with collections:

Now I can't imagine all such small code fragments implemented with IF-statements and elvis operators. So, how such things will be going in Kotlin?

I'm new to Kotlin, but I really like its null-safety features with the various uses of '?'. It's all very consistent and elegant.

But here's a suggestion: the only place where you don't use the ? symbol is in the keyword null itself. This is inconsistent (and seems old-fashioned, like the ugly days of C++) - and of course null hardly ever needs to be mentioned in code anyway.

Thanks for your suggestion, but im my opinion, this would make the syntax cumbersome and unfamiliar where it need not be. Also, while unambigous for the compiler, it will be rather ambiguous for the eye.

> Note that this only works where b is immutable (i.e. a local val or a member val which has a backing field and is not overridable), because otherwise it might happen that b changes to null after the check.

Is this why in Swift you have to `if let temp = value`? Hmm... maybe Kotlin should offer the same? However, if this is just to prevent multithreaded race conditions, then the restriction seems rather excessive. (The vast majority of code is not touching shared variables, moreover without locking, and code that is has enough potential dangers that it wouldn't matter much if this were another.)