h1. 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"|http://qconlondon.com/london-2009/presentation/Null+References:+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}}:
{jet}
var a : String = "abc"
a = <error desc="Incompatible types: cannot assign null to a variable of type String">null</error> // compilation error
{jet}
To allow nulls, one declares a variable as _nullable string_, written {{String?}}:
{jet}
var b : String? = "abc"
b = null // ok
{jet}
Now, if you call a method on {{a}}, it's guaranteed not to cause an {{NPE}}, so you can safely say
{jet}
val l = a.length()
{jet}
But if you want to call the same method on {{b}}, that would not be safe, and the compiler reports an error:
{anchor:example}
{jet}
val l = b<error desc="'b' can be null. Use safe call (?.) or check for null explicitly">.</error>length() // error: variable 'b' can be null
{jet}
But we still need to call that method, right? There are a few ways of doing that.

h2. Checking for {{null}} in conditions

First, you can explicitly check if {{b}} _is_ {{null}}, and handle the two options separately:
{jet}
val l = if (b != null) b.length() else -1
{jet}
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:
{jet}
if (b != null && b.length() > 0)
  print("String of length ${b.length()}")
else
  print("Empty string")
{jet}

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.

h2. Safe calls

Your second option is the _safe call_ operator, written {{?.}}:
{jet}
b?.length()
{jet}
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:
{jet}
bob?.department?.head?.name
{jet}
Such a chain returns {{null}} if any of the properties in it is {{null}}.

h2. 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}}":
{jet}
val l : Int = if (b != null) b.length() else -1
{jet}
Along with the complete {{if}} expression, this can be expressed with the _Elvis_ operator, written {{?:}}:
{jet}
val l = b?.length() ?: -1
{jet}
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*.

{anchor:sure}
h2. 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|#example]) or throw an {{NPE}} if {{b}} is {{null}}:
{jet}
val l = b!!.length()
{jet}
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:
{jet}
inline fun <T : Any> T?.sure() : T =
  if (this == null)
    throw NullPointerException()
  else
    this
{jet}

h1. 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:
{jet}
val aInt : Int? = a as? Int
{jet}

h1. Best practices related to this feature

[J. Bloch, Effective Java. Second Edition |http://java.sun.com/docs/books/effective/]
*Item 38*: Check parameters for validity
*Item 43*: Return empty arrays or collections, not nulls


[Null Object Design Pattern |http://en.wikipedia.org/wiki/Null_Object_pattern]
(Originally proposed by [B. Woolf |http://portal.acm.org/citation.cfm?id=273448.273450])

h1. 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*|http://www.jetbrains.com/idea/documentation/howto.html].

*Scala* promotes using the [{{Option}} type |http://www.scala-lang.org/api/current/scala/Option.html] 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.

*Groovy* has [Safe navigation |http://docs.codehaus.org/display/GROOVY/Operators#Operators-SafeNavigationOperator%28%3F.%29] and [Elvis |http://docs.codehaus.org/display/GROOVY/Operators#Operators-ElvisOperator%28%3F%3A%29] operators.

*Gosu*'s [approach |http://gosu-lang.org/doc/wwhelp/wwhimpl/api.htm?&context=gosu&src=expressions&topic=Handling_Null_Values_In_Expressions] is close to ours.

h3. What's next

* [Exceptions]