Smartcast for nullable variable properties

@arocnies Thanks for the hint, I will use it as well. Yes, I know about working smart cast on local variables (unless they are captured in some non-inline closures!).

Of course you could still be stuck in a project where mutable state is prevalent and you aren’t in a position to fix it.

The point is that the Kotlin (especially JVM) is not designed as functional language/platform. Writing code in pure functional style may end up with tons of data being copied around. Truly functional languages, e.g. Haskell, have special implementation under the hood which prevents data copying wherever possible (among with other things which make its runtime different from imperative languages). So writing everything functional may not always be a good idea in an imperative language.
Anyway, thanks for the help! At least new idoms learned.

Gotcha :slight_smile:

Just to note that multi-assignment isn’t possible in Kotlin right now but I’ve seen it debated elsewhere. I’d be interested to see what other idea’s people have if they are also dealing with capturing lots of non-final variables.

I just don’t think the unsafe smart-casts are the right answer, IMHO.

(Maybe there’s no good alternative and it’s just a good code smell that helps coders know when to refactor).

Oh, wow… I’ve been writing a lot of Kotlin for a couple of years now and never used !! (maybe except in a few unit tests where I was just lazy to actually do assertions that would have the same effect of just causing the test to fail). If you’re using it in Kotlin, I invite you to try to learn new ways of writing code which make var basically non-existent in the code base, and specially nullable vars - trust me, it’s not hard, and I am definitely not talking about pure FP here. Mutability outside of local variables, in general, makes code extremely hard to reason about, as many other posters have explained above… but if you keep to your conviction that it’ fine to use nullable, mutable state all over your code, then I would kindly suggest you should stick with Java as what you’re asking for is a unsafe Java construct, the kind of bug-prone thing whose elimination is the whole reason for Kotlin to exist.

2 Likes

Another idea that would make the original code easier to write would be the if let construct from Swift and Rust:

var maxSize: Int? = null

fun doSomething() {
    val doRoll = if (let max = maxSize) {
        // max not null here
       size >= max
    } else false
}

Well it does

val doRoll = maxSize?.let { size >= it } ?: false
2 Likes