4

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()?

Lior Bar-On
  • 10,784
  • 5
  • 34
  • 46
TN.
  • 18,874
  • 30
  • 99
  • 157
  • Learn more about Kotlin nullable types and operators and methods for dealing with them: http://stackoverflow.com/questions/34498562/in-kotlin-what-is-the-idiomatic-way-to-deal-with-nullable-values-referencing-o – Jayson Minard Dec 29 '15 at 20:20

1 Answers1

3

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.

Ilya Ryzhenkov
  • 11,782
  • 1
  • 40
  • 50
Andrey Breslav
  • 24,795
  • 10
  • 66
  • 61
  • Is there a similar feedback from dogfooding? (Since `!!` makes the code not really nice.) – TN. May 21 '14 at 12:50
  • 1
    @TN. It's a tradeoff: fast compiler/robust library vs more convenience. Nobody thinks it's very beautiful. If we come up with something elegant enough yet powerful, we'll definitely improve on such use cases. – Andrey Breslav May 21 '14 at 19:29
  • I thought that inline functions are similar to macros, so it might work without extra features, or? – TN. May 21 '14 at 20:24
  • @TN. Conceptually, inline functions are similar to (very restricted) macros, but in fact the efficient internal representation we use implies some extra work needed to support this. – Andrey Breslav May 22 '14 at 03:10
  • One of these options is in YouTrack as: https://youtrack.jetbrains.com/issue/KT-8889 Basically an idea to express a contract, if input values have some conditions then output will as well. Or maybe some simple definitions based only around nullability since it is the biggest gain from something like this. – Jayson Minard Dec 29 '15 at 20:23