Hello! Is there a way to somehow assign variables ...
# announcements
i
Hello! Is there a way to somehow assign variables in the left side expression of a
when
clause, to be used in the right side?
Copy code
when {
    toFoo(line) != null -> elements.add(toFoo(line)) // reuse left side result instead?
}
p
In your example you try to reuse not the whole expression on the left
toFoo(line) != null
but just part of it
tooFoo(line)
. I would recommend to try to rewrite your code using different constructs. For example, you can write
Copy code
toFoo(line)?.let { elements.add(it) }
i
but then I can’t use them in a
when
expression, no?
s
why not just do
Copy code
toFoo(line).let { fooLine ->
when {
   fooLine != null -> doSomething
   else -> do2
 }
}
or
Copy code
val fooLine = toFoo(line)
when {
  fooLine != null -> doSomething
  else -> do2
}
i
@sitepodmatt the problem with that it that it forces me to always call the method
by having it in the clause it’s evaluated only if all the previous branches didn’t match
but I get it that it’s not possible it seems
p
you can use
by lazy
for local variable
Copy code
val fooLine by lazy { toFoo(line) }
i
oh that’s good, thanks!
hm… not critical, but it would have been great if smart casting was possible. But with the lazy val it’s not possible 😕
I mean such that the value isn’t optional on the right side anymore