Ginanjar Setiawan
Ginanjar Setiawan

Reputation: 166

how to set multiple kotlin variables in one line

I want to fill two variables in the same line, but I don't know the best way to do it at kotlin

var a:String? = null
var b:String? = null
a, b = "Text"

Upvotes: 1

Views: 2001

Answers (3)

Source
Source

Reputation: 309

Simply create an inline array, iterate through and assign values.

listOf(a, b, c, d).forEach { it = "Text" }

Upvotes: 2

ysakhno
ysakhno

Reputation: 863

Not possible in Kotlin (unless you are ready to resort to some contrived constructs with repetition as described in other answers and comments). You cannot even write

    a = b = "Text"

because weirdly enough, assignments are not expressions in Kotlin (as opposed to almost everything else like if, return, throw, swicth, etc., which are expressions in Kotlin, but not in Java, for example).

So, if you want to assign exactly the same value without repetition (of the assigned value), you'll have to write

    a = "Text"
    b = a

Note, that there is also an also function (pun intended), so technically you can write the following if you really want to stay on one line

    a = "Text".also { b = it }

but I doubt it is really worth it.

Upvotes: 4

alexanderktx
alexanderktx

Reputation: 158

var a: String? = null; var b: String? = null

or

var (a: String?, b: String?) = null to null

But please don't ever do so

Upvotes: 2

Related Questions