Learning Kotlin: Nullable Types

Submitted by Robert MacLean on Mon, 06/25/2018 - 09:00

More Information

The next Koan looks at how Kotlin handles nulls, and it does it wonderfully; Null is explicitly opt-in. For example, in C# you can assign null to a string variable but in Kotlin unless you say you want to support nulls, which you do by adding a trailing question mark to the class, you cannot.

Their example in this Koan is a nice example:

  1. fun test() {
  2.     val s: String = "this variable cannot store null references"
  3.     val q: String? = null
  4.  
  5.     if (q != null) q.length      // you have to check to dereference
  6.     val i: Int? = q?.length      // null
  7.     val j: Int = q?.length ?: 0  // 0
  8. }

Let us dig into the Koan, where we get given the following Java code:

  1. public void sendMessageToClient(@Nullable Client client, @Nullable String message, @NotNull Mailer mailer) {
  2.     if (client == null || message == null) return;
  3.  
  4.     PersonalInfo personalInfo = client.getPersonalInfo();
  5.     if (personalInfo == null) return;
  6.  
  7.     String email = personalInfo.getEmail();
  8.     if (email == null) return;
  9.  
  10.     mailer.sendMessage(email, message);
  11. }

and we need are going to rewrite it using the Nullable language features of Kotlin, which looks like:

  1. fun sendMessageToClient(client: Client?, message: String?, mailer: Mailer) {
  2.     val email = client?.personalInfo?.email
  3.     if (email == null || message == null) return
  4.  
  5.     mailer.sendMessage(email, message)
  6. }

The big changes from Java:

  1. The @NotNull attribute for mailer is no longer needed
  2. The @Null attribute for the other parameters becomes the question mark
  3. We do not need to pre-check client before calling the parameter, as you can use the null safe operator ?. to ensure you only check before we call the method.
  4. Unfortunately, the null safe operator in Kotlin doesn't support calling methods on null objects as C# currently does with its Elvis operator