Unit-Insertion works differently in Scala 2 & Scala 3
See original GitHub issueScala 3 handles unit-insertion differently to Scala 2
Compiler version
3.0.0 vs 2.13.6 - both using Scastie
Minimized code
val f: Boolean => Any = g => {
if (g)
1
}
println(f(true))
println(f(false))
Output - using Scala 3…
()
()
plus warning…
A pure expression does nothing in statement position; you may be omitting necessary parentheses
Expectation - as in Scala 2…
1
()
plus no warning
Comments
Scala 3 does give the above warning about a pure expression and changing the code to the following works…
val f: Boolean => Any = g => {
if (g)
1
else
()
}
}
println(f(true))
println(f(false))
From @smarter … “it looks like unit-insertion is working differently in scala 2 and 3 (in scala 2 it only inserts Unit in the missing branch, in Scala 3 it inserts it in both branches)”
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:5 (2 by maintainers)
Top Results From Across the Web
Compatibility Reference | Scala 3 Migration Guide
This chapter describes the compatibility between Scala 2.13 and Scala 3. ... compatibility between the two versions at the different stages of the...
Read more >Classpath Level | Scala 3 Migration Guide
In your code you can use public types and terms, and call public methods that are defined in a different module or library....
Read more >New in Scala 3
The exciting new version of Scala 3 brings many improvements and new features. Here we provide you with a quick overview of the...
Read more >Forward Compatibility for the Scala 3 Transition
To illustrate this scenario, we will start with an empty directory and build an sbt project with Scala 2.13 that has two modules,...
Read more >Scala 3 Syntax Rewriting
In this chapter we show how you can use the compiler to rewrite your code automatically from the classic Scala 2 style to...
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 Free
Top 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
The behavior is specified:
Also the feature is not called “Unit insertion” (which sounds helpful) but “Value discard” (which sounds possibly dangerous).
I saw a tailrec method of the form
def f: Unit = if (b) f
and wondered does that even compile. It compiles forUnit
result but not forAny
. The Scala 2 rule, thatif (b) expr
meansif (b) expr else ()
, is much easier to reason about, in that there is nothing to reason about.