‘if … else if’ expression unexpectedly has Unit value when last branch taken
See original GitHub issueCompiler version
3.1.1
Minimized code
This code prints ()
, as a
evaluates to the Unit
value:
val a =
if false then
1
else if true then
2
println(a)
Update: this code may be a bit too minimized to demonstrate the scope of the actual problem. See the examples in this comment for more clarity.
Output
()
Expectation
Although this code is unusual and unlikely to be written by an experienced programmer (it is a simplified and minimized version of something written by my 8-year-old son who has just started learning to program with Scala), I suspect most people would intuitively expect a
to evaluate to 2
rather than to ()
.
Adding an unconditional else
clause to the if
statement restores expected behaviour:
val a =
if false then
1
else if true then
2
else
3
println(a) // prints 2
Issue Analytics
- State:
- Created a year ago
- Comments:13
Top Results From Across the Web
Why Kotlin compiler gives an error in a valid IF statement?
It REQUIRES a return value from within the lambda, and last statement inside it is when block so it is used as an...
Read more >Missing "else" changes branch percentage #35 - GitHub
This is a feature. It tells you that you don't have a test case where the "empty else block that notionally exists" is...
Read more >C#'s cascaded if statement: evaluate multiple conditions
C#'s cascaded if statement evaluates a series of true/false expressions. The one that's true has its code block execute.
Read more >Comp Sci Chapter 4 Flashcards - Quizlet
The last branch is not just "else" but has an expression. nested if-else statements. The first branch executes, which is a nested if-else....
Read more >If Statements, Loops and Recursions · OCaml Tutorials
If statements (actually, these are if expressions). OCaml has an if statement with two variations, and the obvious meaning: if boolean- ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@KacperFKorban hi, if you agree, would you mind reopening? My previous judgment may have been premature. Or, we could start a discussion in discussions.
That’s pretty funky. Just the penultimate branch (before the missing else) gets its value discarded (as I now see you said). That must be a glitch.