Multiple variable affectation

Greetings,

Let’s assume I’ve a map (passwords) that contains three values (old password, new password and confirm password).

To process the checking before I make the change, I may need to assign those 3 values into variables (oldPassword, newPassword and confirmPassword).

The normal pattern is :
val oldPassword = passwords[“old”]
val newPassword = passwords[“new”]
val confirmPassword = passwords[“confirm”]

I’ve to declare those 3 affectations into 3 different lines.

What we could declare something like :
val (oldPassword, newPassword, confirmPassword) = (passwords["old], passwords[“new”], passwords[“confirm”])

?

Thanks.

Your code would work if you just add arrayOf or listOf:

val (oldPassword, newPassword, confirmPassword) = arrayOf(passwords["old"], passwords["new"], passwords["confirm"])

You can also create a very simple extension for picking multiple values from a map, then do:

fun main() {
    val passwords = mapOf("old" to "123", "new" to "456", "confirm" to "789")
    val (oldPassword, newPassword, confirmPassword) = passwords.getValues("old", "new", "confirm")
}

fun <K, V> Map<K, V>.getValues(vararg keys: K): List<V> = keys.map { getValue(it) }

Magic of well-designed language.

In both cases you create unnecessary array/list, so it is potentially less performant than separate assignments.

1 Like

If you’re going to want three separate variables, do you really need a map in the first place?

IMO a map with a fixed set of keys that you know at compile time is a code smell; would it be better as a data class? Or, since it’s only three variables, do they really need a structure at all, or could you simply have three variables from the start?

1 Like

I suggest

data class Passwords(
    val oldPassword: String,
    val newPassword: String,
    val confirmPassword: String
)

You can even destructure it:

fun doSomething(passwords: Passwords) {
    val (old, new, confirm) = passwords
}