TN.
TN.

Reputation: 19770

Kotlin null safety?

Let's have a function foo and a class Bar:

fun foo(key: String): String? {
  // returns string or null
}

class Bar(x: String, y: String) {
  // ...
}

Now, let's have the code:

val x = foo("x")
val y = foo("y")
if (x.isNotEmpty() && y.isNotEmpty())
  return Bar(x, y)

The problem is that this code will not compile. Since it needs the Bar(x!!, y!!).

However when I replace the function with its content, !! are not needed.

val x = foo("x")
val y = foo("y")
if ((x != null && x.length() > 0) && (y != null && y.length() > 0))
  return Bar(x, y)

Why it is not possible to resolve the null check from the function .isNotEmpty()?

Upvotes: 4

Views: 769

Answers (1)

Andrey Breslav
Andrey Breslav

Reputation: 25757

This is possible in theory, but it would mean that either 1. The declaration of isNotEmpty() must convey to the compiler the fact that x is guaranteed to be non-null if the result is true 2. A change to a body of any function may cause its call sites to fail to compile.

Option 2 is definitely unacceptable. Option 1 requires a rather expressive mechanism in the type system, which we decided not to add at the moment, because it is likely to complicate things for the user.

We are planning to support something like this with inline functions, but it's still under consideration.

Upvotes: 3

Related Questions