wilddev
wilddev

Reputation: 1964

Kotlin canonical way to initialize two or more vals by some conditions

What is the canonical way of initializing two (or more) vals by condition?

var a : Int;// I want this to be val, not var
var b: Int;// I want this to be val, not var too

if(condition) {
 a = 1
 b = 2
} else {
 a = 3
 b = 4
}

Using "if" several times is not convenient, as there could be lots of vars and lots of conditions

val a = if(condition) 1 else 2
val b = if(condition) 3 else 4

Upvotes: 0

Views: 673

Answers (4)

Feedforward
Feedforward

Reputation: 4869

You can use Destructuring Declarations for this purpose.

val (a, b, c) = if (condition) listOf(1, 2, 3) else listOf(4, 5, 6)

For different types you can combine it with object creation:

data class ValueInitializer(
    val a: Int,
    val b: String
)

val (a: Int, b: String) = if (condition) 
         ValueInitializer(1, "String") 
    else 
         ValueInitializer(2, "String2")

Another point is that you can use val instead of var in your first example if a and b are local variables. For class fields you can initialize them inside init block, or mark them with lateinit modifier.

Upvotes: 2

leonardkraemer
leonardkraemer

Reputation: 6813

If you initialize in the init-block (or the constructor) you can use val which looks very clean and uses only one if:

class foo(){
    val a : Int
    val b : Int

    init{
        if(condition) {
            a = 1
            b = 2
        } else {
            a = 3
            b = 4
        }
    }
}

Otherwise I would advise to read the initialisation from a config file, if there are many variables. In the spirit of decoupling code and data.

Upvotes: 0

gidds
gidds

Reputation: 18607

While using tuples and destructuring is nice and concise, you can just use val instead of var in the question's code!

(I tried it, and it works fine for me in IDEA with Kotlin 1.3.10.)

In Java, each of those would be called a 'blank final'; I don't know if Kotlin uses the same term. In any case, as long as the compiler can see that such a variable always gets initialised exactly once (which they do here), it's happy.

Upvotes: 3

algebraic
algebraic

Reputation: 311

You can do that using Pair destructuring:

val (a, b) = if (condition) 1 to 2 else 3 to 4

You can read more in the documentation: https://kotlinlang.org/docs/reference/multi-declarations.html#destructuring-declarations

For 3 variables you can use Triple:

val (a, b, c) = if (condition) Triple(1, 2, 3) else Triple(3, 4, 5)

Upvotes: 3

Related Questions