Kotlin and idiomatic way to write, 'if not null, else...' based around mutable value : <p>Suppose we have this code:</p>

<pre><code>class QuickExample {

    fun function(argument: SomeOtherClass) {
        if (argument.mutableProperty != null ) {
            doSomething(argument.mutableProperty)
        } else {
            doOtherThing()
        }
    }

    fun doSomething(argument: Object) {}

    fun doOtherThing() {}
}

class SomeOtherClass {
    var mutableProperty: Object? = null
}
</code></pre>

<p>Unlike in Java, where you could be left alone to worry about null dereferencing at runtime, this doesn't compile - quite rightly. Of course, <code>mutableProperty</code> may no longer be null once within the 'if'.</p>

<p>My question is what's the best way to handle this?</p>

<p>A few options are apparent. Without using any new Kotlin language features, the simplest way is obviously to copy the value to a method-scope one that won't subsequently change.</p>

<p>There's this:</p>

<pre><code>fun function(argument: SomeOtherClass) {
    argument.mutableProperty?.let {
        doSomething(it)
        return
    }
    doOtherThing()
}
</code></pre>

<p>This has the obvious disadvantage that you need to return early or otherwise avoid executing the subsequent code - OK in certain, small contexts, but has a smell to it.</p>

<p>Then there's this possibility:</p>

<pre><code>fun function(argument: SomeOtherClass) {
    argument.mutableProperty.let {
        when {
            it != null -&gt; {
                doSomething(it)
            }
            else -&gt; {
                doOtherThing()
            }
        }
    }
}
</code></pre>

<p>but whilst it has greater clarity of purpose, arguably it's more unwieldy and verbose than the Java-style way of dealing with this.</p>

<p>Am I missing anything, and is there a preferred idiom with which to achieve this?</p>
