Kotlin - zero security?

Let there be a function fooand a class Bar:

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

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

Now let's specify 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. Because this is required Bar(x!!, y!!).

However, when I replace the function with my content, it is !!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 is it impossible to solve a null check from a function .isNotEmpty()?

+4
source share
1 answer

This is possible in theory, but this will mean that either 1. The isNotEmpty () declaration should convey to the compiler the fact that x is guaranteed to be non-empty if the result is true 2. Changing the body of any function may make it impossible to compile its call sites.

2 . 1 , , , , .

- , .

+3

Source: https://habr.com/ru/post/1541396/


All Articles