https://kotlinlang.org logo
#codereview
Title
# codereview
m

Mike

01/16/2019, 12:49 PM
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

Pavlo Liapota

01/16/2019, 12:56 PM
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

Mike

01/16/2019, 12:59 PM
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.
4 Views