No warning on discarded value

The following code runs with no warning:

def f(x: Int) =
  if x <= 0 then None
  x / 2

println(f(-2)) // -1

Shouldn’t this print a ‘non-Unit value was discarded’ warning? Scastie: Scastie - An interactive playground for Scala.

I’m working on a Scala 2 PR to help warn, but Scala 3 has fewer warnings.

In current Scala 2, even invoking a singleton None may be side-effecting, so it doesn’t warn. (Creating a singleton may be side-effecting the first time.)

It’s also true that Scala 3 sees if (b) v as inherently discarding, whereas Scala 2 sees if (b) v else (). I haven’t looked at how to warn in that case yet.

1 Like