https://kotlinlang.org logo
#announcements
Title
# announcements
p

Pablichjenkov

07/28/2019, 5:42 AM
I found myself doing bellow code very often when having a nullable variable in a class. Is there a less verbose pattern?
Copy code
class SomeClass {
 
    var aVar: OtherClass? = null

    fun aFunction() {

        aVar?.let {
            //doSomething with aVar since 'it' is not null
        } ?: run {
            //doSomething else when aVar is null
        }

    }

}
I know that I can do this:
Copy code
fun aFunction() {

    val aVarLocalCopy = aVar

    if (aVarLocalCopy != null) {
            //doSomething with aVarLocalCopy
    } else {
            //doSomething else when aVarLocalCopy is null
    }

}
But I don’t like the fact of creating one line of code to extract the thread safe local reference copy of aVarProperty. Any pattern or extension function to write above code shorter.
s

Shawn

07/28/2019, 5:54 AM
I don’t think this is particularly verbose, buuuut I mean, you could use a when
Copy code
fun aFunction() {
    when (val aVarLocalCopy = aVar) {
        null -> {

        }
        else -> {

    }
  }
}
it’s worth mentioning that you wouldn’t really be making a copy of
aVarProperty
, you’d just be making a new immutable copy of the reference
p

Pablichjenkov

07/28/2019, 6:32 AM
yes, that I am aware of. I guess the real copy only happens if
aVar
is a primitive. Anyways, back to the original question.
When
looks pretty neat, in fact a co-worker had suggested that too, just wanted to see what others are doing. Thanks Shawn
👍 1