Defining null and non-null types

How to best work with, and eliminate, null from Kotlin is a very relevant and important topic, and the presence of non-null types is one of the biggest differences between Java and Kotlin. Having some discussion around this key distinction is important key to learning Kotlin and understanding further concepts around null-safe calls, scoping operators, and so on. Before learning more about working with null, let's look at how we would define a non-null value. In the following snippet, you'll see we create a variable named language of the String type:

fun main(args: Array<String>) {
var language: String = "Kotlin"
}

If we want to assign a null value to our language variable, we will get a compiler error:

fun main(args: Array<String>) {
var language: String = "Kotlin"
// Error: Null can not be a value of a non-null type String
language = null
}

This is because types in Kotlin are non-null by default, and so our language variable will only accept String (non-null) types. To allow a variable to accept a null reference, it must be explicitly declared as accepting nullable values:

fun main(args: Array<String>) {
var language: String = "Kotlin"
language = null // Error: cannot be null

var name: String? = "Kotlin"
name = null // this is okay
}

In this case, the name variable is defined as the String? type. To indicate that a variable should accept null values, you must add ? after the type.