can i use when in Kotlin to change the value of an existing variable?
i understand this one:
val num = 1
val result = when {
num > 0 -> "positive"
num < 0 -> "negative"
else -> "zero"
}
println(result)
should be "positive"
but i want this( psuedo )....
val num = 1
var result = "init string"
//bunch of code here
// later....
result = when{
num > 0 -> "positive"
num < 0 -> "negative"
else -> "zero"
}
it writes positive, but it says "Variable "result" initializer is redundant.
What im missing here? Thx
CodePudding user response:
The line
var result = "init string"
is redundant because you leave no possibility of that value not getting overridden in the when
statement. "init string"
cannot be printed at the end of the code, the variable will always have one of the three possible values defined in the when
.
But you can directly initialize result
with the when
statement:
fun main() {
var num = 1
// directly assign the result of the when statment to the variable
var result = when {
num > 0 -> "positive"
num < 0 -> "negative"
else -> "zero"
}
println(result)
}
This prints
positive
CodePudding user response:
thank you for the answer.
But i can say....
fun main() {
var num = 1
// directly assign the result of the when statment to the variable
var result = when {
num > 0 -> "positive"
num < 0 -> "negative"
else -> "zero"
}
println(result)
// and then later reassign....
num = 2
result = when{
num == 2 -> "two"
else -> "not two"
{
println(result)
// prints two
}
So i cant reassign an existing string with a when statement, that is not initialized with an another when statement?
I hope this is readable. :)
Thank you.
dagogi