Instruction 1

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Understanding the Null Data Type

Null is a data type that signifies nothing. It’s not 0, and it’s not an empty set or string. It signifies there’s nothing there at all. It’s non-existent. This isn’t in itself a bad thing. But what happens is that you usually do not design your program thinking that a value would be null. Then, during program execution, some invalid, null data could get set. The null could come from a user, a network issue, or some other unanticipated scenario. Kotlin has near-direct interoperability with Java. Your code can likely access some Java functionality. But Java doesn’t have these null safety features. Java could provide your Kotlin with an unchecked null. This is a major source of nulls in a Kotlin program.

fun main() {
   val items: String? = null

   if (items == null){
      println("Invalid data")
   }

    println(items.uppercase())
}
fun main() {
   val items: String? = null

   try {
      println(items!!.uppercase())
   }
   catch(e: NullPointerException) {
      println("Invalid data")
   }
}

Initializing A Non-Nullable

Kotlin’s null-safety begins with making a data type nullable. You’ll start with a non-nullable type. You define this type the same as you always do by specifying a non-null value:

fun main() {
   val items = 2
   println(items)
}
fun main() {
   val items: Int = 2
   println(items)
}

Initializing A Nullable

To handle nullable values, you have to append ? after the type when declaring the variable:

fun main() {
   val items: Int? = null
   println(items)
}
fun main() {
   val items = null
   println(items)
}
See forum comments
Download course materials from Github
Previous: Introduction Next: Instruction 2