6

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?

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This is closer but not actual solution i was looking. Java has support but seems that Kotlin doesn't.
I don't think the second way is any more idiomatic than the first one.
"Java has support but seems that Kotlin doesn't.". Correct. Kotlin has avoided the mistake of supporting this. The answer explains why it's a mistake.
6

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.

1 Comment

Best option for this use case in Kotlin.
1

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);

1 Comment

Aware of this syntax. Not helpful in my case. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.