Muneesh
Muneesh

Reputation: 463

How to assign same value to multiple variables in Kotlin

I have two variables and I want to assign the same value to both of them at the same time, something like below:

var allGood: Boolean = false
val deviceId: String = "3550200583"
var isValidId: Boolean = false
allGood = isValidId = deviceId.length > 0 && deviceId.length <= 16

Is there any way to achieve this?

Upvotes: 6

Views: 8852

Answers (3)

E.M.
E.M.

Reputation: 4547

What about:

var allGood: Boolean = false
val deviceId: String = ...
val isValidId: Boolean = (deviceId.length in 1..16).also { allGood = it }

.also allows you to perform additional operations with the value that it receives and then returns the original value.

Upvotes: 6

gidds
gidds

Reputation: 18557

Because assignment is not an expression in Kotlin, you can't do multiple assignments that way.  But there are other ways.  The most obvious is simply:

isValidId = deviceId.length > 0 && deviceId.length <= 16
allGood = isValidId

A more idiomatic (if longer) way is:

(deviceId.length > 0 && deviceId.length <= 16).let {
    allGood = it
    isValidId = it
}

(By the way, you can simplify the condition to deviceId.length in 1..16.)

There are a couple of reasons why Kotlin doesn't allow this.  The main one is that it's incompatible with the syntax for calling a function with named parameters: fn(paramName = value).  But it also avoids any confusion between = and == (which could otherwise cause hard-to-spot bugs).  See also here.

Upvotes: 12

Gal Naor
Gal Naor

Reputation: 2397

Another way is to do it like this:

val deviceId: String = "3550200583";
val condition = deviceId.length > 0 && deviceId.length <= 16
var (allGood, isValidId) = arrayOf(condition, condition);

Upvotes: 1

Related Questions