user1785730
user1785730

Reputation: 3525

How to deal with nullable variables that are not null?

Consider this piece of code:

var foo: Foo? = null

if (foo != null) {
    foo!!.bar()
}

If I omit the two !! I get this error:

Smart cast to 'Foo' is impossible, because 'foo' is a mutable property that could have been changed by this time

This is about concurrency, right? Well, there is no concurrent code that might change the value of foo.

Of course, it works with the two !!. However, I was wondering if this is the most idiomatice way or if there is a better way, without the two !!.

I know I could just foo?.bar() in this particular case. But the question is about whether I can treat foo as Foo instead of Foo? somehow after I've checked that it's not null.

Upvotes: 1

Views: 102

Answers (1)

madhead
madhead

Reputation: 33374

Well, this piece of code works if foo is a local variable. I guess, your code looks a little bit different and foo is a field of a class. The solution is simple: use let:

foo?.let {
    it.bar()
}

let "captures" the values of a variable so that any modifications to the original one have no effect in the passed lambda. And safe call is used here to invoke let only for non-null values.

Upvotes: 3

Related Questions