Jonathan Stellwag
Jonathan Stellwag

Reputation: 4267

Kotlin - conditional assign value in one line

Is it possible to conditional assign a value in one line in kotlin?

Setup

var foo: String

if (x != 0) {
  foo = x
}

Goal

// nothing is set if condition is false
foo = if (x != 0) x

Not wanted

// null is set if condition is false
foo = takeIf{ x != 0 }.let{ x }

Upvotes: 4

Views: 9180

Answers (3)

Joffrey
Joffrey

Reputation: 37680

The usual way of doing this would be the following:

if (x != 0) foo = x

This is not always possible, because smart casting cannot be performed if there is a chance that another thread modifies the value between the null check in the assignment. This happens for instance if your x is a nullable var property on the class.

In that case, you have this option:

x?.let { foo = it }

Upvotes: 3

jperl
jperl

Reputation: 5112

Sure thing

if (x != 0) foo = x

Upvotes: 5

Geno Chen
Geno Chen

Reputation: 5214

Is

foo = if (x != 0) x else foo

you want?

(Besides, you declared var foo: String, and the x != 0 may indicate a x: Int, then you are not able to foo = x. Maybe a typo here.)

Upvotes: 11

Related Questions