rtsketo
rtsketo

Reputation: 1246

Kotlin: Check for Null and Assign?

var something: Something? = null
val notNull: Something = ...

...

fun getSomething() {
    something = something ?: notNull
    return something
}

Is there in Kotlin any way to do both something = something ?: notNull; return something at the same time?

Or.. even better, is there a way to do it with generics in an inline function?

Upvotes: 1

Views: 223

Answers (1)

IR42
IR42

Reputation: 9682

fun getSomething(): Something {
    return something ?: notNull.also { something = it }
}
// or 
fun getSomething(): Something = something ?: notNull.also { something = it }

Upvotes: 3

Related Questions