Ahmed Hegazy
Ahmed Hegazy

Reputation: 12615

Immutable val null check inside extension function

When I have an immutable val optional, the compiler tracks the information about the check I performed for null and can treat the variable as non null and call it directly inside the if condition.

val s: String? = "test"

if (s != null) {
   s.startsWith("3") // This works
}

if (!s.isNullOrEmpty()) {
    s.startsWith("3") // Not working
}

Is it possible to make that check in an extension function and keep the compiler aware of it?

Upvotes: 2

Views: 131

Answers (1)

Henning
Henning

Reputation: 11696

This is not yet available in Kotlin.

There is a feature called "Contracts" which is currently developed at JetBrains (https://discuss.kotlinlang.org/t/status-of-kotlin-internal-contracts/6392) – it's similar to what they've done with their own @Contract annotation for Java code, but will have support from the compiler.

However, it's in early stages and there is no release date yet.

Upvotes: 4

Related Questions