assign variable only if it is null

Viewed 16771

on Ruby one have something like this:

@var ||= 'value' 

basically, it means that @var will be assigned 'value' only if @var is not assigned yet (e.g. if @var is nil)

I'm looking for the same on Kotlin, but so far, the closest thing would be the elvis operator. Is there something like that and I missed the documentation?

2 Answers

Other way we could do it is by using ifEmpty..

From the docs: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/if-empty.html

Usage:

val empty = ""

val emptyOrNull: String? = empty.ifEmpty { null }
println(emptyOrNull) // null

val emptyOrDefault = empty.ifEmpty { "default" }
println(emptyOrDefault) // default

val nonEmpty = "abc"
val sameString = nonEmpty.ifEmpty { "def" }
println(sameString) // abc

EDIT: Seems like this does not work if the initial value is NULL and only for strings..

Related