test(1) results in “12.0” test(2) results in “13.0...
# codereview
m
test(1) results in “12.0” test(2) results in “13.0" Ran in Scratch file of IntelliJ, hence no
println
What am I missing? I would have expected the val to require an initial value, and complain if it’s assigned, but it appears not.
p
Compiler can do control flow analysis. In your example
local
variable is always assigned before it is used and never reassigned, so it is fine by compiler.
You can look at it like:
Copy code
val local =
    if (a == 1)
        "12.0".toBigDecimal()
    else
        "13.0".toBigDecimal()
return local
👍 1
m
Interesting. So even though there’s more code, it still does that level of analysis. Nice! Just hadn’t thought of using it before, and it’s definitely a rare scenario where it makes sense over using
if
as an expression, but nice to know it’s there.