Instruction 3

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

Working With the Null Assertion Operator

This operator asserts that an object, though nullable, isn’t null. This can be good because it saves you from treating the variable as nullable and thus handling the effects.

fun main() {
  var fruit: String? = null
  fruit = "Salad"
  println(fruit!!.uppercase())
}
fun main() {
  val fruit: String? = null
  println(fruit!!.uppercase())
}
Exception in thread "main" java.lang.NullPointerException
at FileKt.main (File.kt:8)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (:-2)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (:-1)

Using the Nullable Receiver

Some functions are defined on nullable receivers. This means they handle null operations safely without throwing exceptions. A good example is the toString() function. If you call toString() on a null object, it returns a “null” string:

fun main() {
  val items = null
  val result = items.toString()
  println(result::class.java.simpleName)
}
String

Working With Safe Casts

To cast one type to another type is to convert one type to another type. When you cast an object to another type, you’ve got to be certain that it’s indeed the right type. You can’t cast an Int to a String. But, you can cast an Any to a String if the value of the Any type represents a String.

fun main() {
  val food: Any = "Corn"
  val staple = food as? Int
  println(staple)
}
null
fun main() {
  val food: Any = "Corn"
  val staple = food as Int
  println(staple)
}
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
at FileKt.main (File.kt:10)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (:-2)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (:-1)

Using Nullable Collections

When collections contain nullable data, you have to be careful how you use it. Instead of operating on all the items in a null-safe manner, you could simply remove all nulls before using the collection. You’ll achieve this using the filterNotNull() method. filterNotNull() is available on all Collection types:

fun main() {
  val fruits = listOf("Pear", "Mango", null, "Orange")
  println(fruits)

  val nonNullFruits = fruits.filterNotNull()
  println(nonNullFruits)
}
See forum comments
Download course materials from Github
Previous: Instruction 2 Next: Demo