How to get "a pure expression does nothing in statement position" Warnings?

1,966 views
Skip to first unread message

Kevin Meredith

unread,
Dec 4, 2015, 8:34:58 PM12/4/15
to scala-user
Will any compiler flags catch this potential programming error:

scala> def f(x: Int): Int = {

     |   if(x == 0)

     |     x

     |   else

     |     55 // I'd prefer a warning here since the if/else falls into the "a pure expression in statement position ..." warning class

     |   42

     | }

f: (x: Int)Int


scala> f(100)

res0: Int = 42

Russ P.

unread,
Dec 5, 2015, 3:24:26 PM12/5/15
to scala-user
I don't know the answer to your question, but I'll venture a guess. Perhaps it isn't easy for the compiler to guarantee that the expression is "pure" (has no side effects). It should be easy in your example I suppose, but in general it isn't.

By the way, I don't understand why you spread the expression over four lines when you can just write

  if (x == 0) x else 55

That sure seems simpler and clearer to me, at least in this trivial example. It also makes it more obvious that you are not using the result of the expression.

Oleksandr Olgashko

unread,
Dec 5, 2015, 3:32:28 PM12/5/15
to Russ P., scala-user
Probably "-Ywarn-value-discard" might be useful here. (Warn when non-Unit expression results are unused)

Also Intellij has "Useless Expression" feature. (Highlights expression if it has no side effects and does not affect on any variable value or function return)

--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages