3

Lets say I have the following class:

class MyClass {
    private var username: String? = null
    private var projectName: String? = null
    private var buildNumber: Int = -1
    private val presenter: Presenter = Presenter()

    fun present() {
        username = ""
        projectName = ""

        if (username != null && projectName != null && buildNumber != -1) {
            presenter.viewReady(this, username, projectName, buildNumber)
        } else {
            throw Exception("You did something bad!")
        }
    }
}

Why is it that I get the error Smart cast to 'String' is impossible, because 'username' is a mutable property that could have been changed by this time?

Is it something to do with not being thread safe?

Based on the null safety docs, I thought this would work for either one of 1. that username and projectName are set in the same function above their use as params and 2. that their use as params is wrapped in an if statement checking their value.

2 Answers 2

7

The Kotlin compiler cannot prove that either username or projectName are mutated by another thread at the same time. The field being private does not help either, as reflection may bypass this.

The relevant documentation for this is under Type Checks and Casts:

Note that smart casts do not work when the compiler cannot guarantee that the variable cannot change between the check and the usage. More specifically, smart casts are applicable according to the following rules:

  • val local variables - always;
  • val properties - if the property is private or internal or the check is performed in the same module where the property is declared. Smart casts aren't applicable to open properties or properties that have custom getters;
  • var local variables - if the variable is not modified between the check and the usage and is not captured in a lambda that modifies it;
  • var properties - never (because the variable can be modified at any time by other code).

Capture the property reference in a local variable instead.

that their use as params is wrapped in an if statement checking their value.

if-statements in Kotlin do not 'capture' a property. When you declare an if-statement including a property and access it again inside the block, the compiler may smart cast it for you. But the rules for accessing are still the same - the getter will be invoked twice.

4
  • 1
    To add to this, if you only had one variable with this issue, you could use username?.let {}, and the it inside would be the non-nullable type, because the let holds on to the value it was called on, ignoring any modifications to the actual variable. Having to do it nested here wouldn't look pretty though.
    – zsmb13
    Apr 23, 2017 at 7:48
  • The easies fix is to use the not-null-assertion operator since you can guaranty the nothing bad happens here: presenter.viewReady(this, username!!, projectName!!, buildNumber)
    – voddan
    Apr 23, 2017 at 8:14
  • @voddan It might be the easiest fix, but getting used to !! will cause you difficult-to-debug problems later down the line.
    – F. George
    Apr 23, 2017 at 21:29
  • @mEQ5aNLrK3lqs3kfSa5HbvsTWe0nIu ok, let me reformulate - using !! IS the correct way of solving problems sometimes, and I shell prove it in my answer
    – voddan
    Apr 24, 2017 at 6:22
2

As @mEQ5aNLrK3lqs3kfSa5HbvsTWe0nIu pointed out, Kotlin does not activate smart casting for var properties. I am not really sure why this strategy was chosen, since private var could be smart-casted in pre-release versions, but that is what we have.

Now, suppose you are sure those properties are not mutated by another thread since they are private and no reflection is used. Thereby the if-null check insures the properties do not contain nulls, but the Kotlin compiler does not believe that.

In such a situation I would strongly recommend using the not-null-assertion operator !!:

presenter.viewReady(this, username!!, projectName!!, buildNumber)

Many recommend avoiding !! to improve your code style, but its meaning is literally "the compiler is dumb, it is obviously not a null, notify me if I am wrong". Situations such as yours are the reason it was introduced in the language in the first place.

There are other workarounds that include saving the current value of the property into a local val (explicitly or implicitly via helper functions), but I believe they are inappropriate here, because they do not express your intent. In some situations you need save-current-value-and-work-with-it semantics, but here you need make-the-compiler-trust-the-code semantics, and they are obviously not the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.