How to workaround value-discard or unused warnnings

While it is recommended to turn on compiler flags like -Wvalue-discard or -Wunused:implicits either explicitly or implicitly throught the use of sbt-tpolecat.

Sometimes you need to workarround those, but in a way that makes it explicit; since we generally consider such things bugs and that was the reason for using the compiler flags in the first place.

One, somewhat common, workarroud for those cases is the following void function (courtesy of Rob Norris).

@inline final def void(args: Any*): Unit = (args, ())._2

However, such function has two problems.

  1. It has a couple of unnecesary extra allocations; namely the Seq for the varargs and the Tuple.
  2. It is not part of the stdlib and adding it on all projects is somewhat tedious.

Is there any other good workarroud that works out of the box?

Upvotes: 4

Views: 1191

Answers (1)

2.13

Since Scala 2.13 there are two ways to disable both warnings.

  1. Assign the values to an non-existent variable:
def testFix1()(implicit i: Int): Unit = {
  val _ = i
  val _ = data
}
  1. Type-ascript the expression to Unit:
def testFix2()(implicit i: Int): Unit = {
  i : Unit
  data : Unit
}

We do not have a formal reference or proof, but it is believed that the second option should be transparent; in the sense that it should not have any impact in runtime, like extra allocations or unwanted code generation.


You can see the code running here.


3.0

As far as we know, the same tricks should work on Scala 3 (aka Dotty).

2.12

???

Upvotes: 3

Related Questions