Excluding type evidence parameters from analysis in Scala when using -Ywarn-unused

1.2k views Asked by At

Compiling a program that contains a type evidence parameter in Scala (such as T <:< U) can cause a warning when -Ywarn-unused is passed to the compiler. Especially in the case when the type evidence parameter is used to verify a constraint encoded using phantom types, this warning is likely to occur.

As an example, compiling the file here: https://github.com/hseeberger/demo-phantom-types/blob/master/src/main/scala/de/heikoseeberger/demophantomtypes/Hacker.scala returns the following:

# scalac -Ywarn-unused Hacker.scala Hacker.scala:42: warning: parameter value ev in method hackOn is never used def hackOn(implicit ev: IsCaffeinated[S]): Hacker[State.Decaffeinated] = { ^ Hacker.scala:47: warning: parameter value ev in method drinkCoffee is never used def drinkCoffee(implicit ev: IsDecaffeinated[S]): Hacker[State.Caffeinated] = { ^ two warnings found

It's clear to me that the parameter ev is not actually necessary at runtime, but the parameter is useful at compile time. Is there any way to instruct the compiler to ignore this case, while still raising the warning for unused function parameters in other contexts?

For example, I think instructing the compiler to ignore implicit parameters of class <:< or =:= would solve this issue, but I'm not sure how that could be accomplished.

2

There are 2 answers

0
Darren Bishop On BEST ANSWER

Many years later, it's worth to mention there is am @unused annotation available (since when, I am not sure):

import scala.annotation.unused

def drinkCoffee(implicit @unused ev: IsDecaffeinated[S]): Hacker[State.Caffeinated]

Consequently, you can not use a context-bounds

0
Oleg Pyzhcov On

I often find myself adding this because of either -Ywarn-unused or -Ywarn-value-discard:

package myproject

package object syntax {
  implicit class IdOps[A](a: A) {
    def unused: Unit = ()
  }
}

Lets you do ev.unused in the code to explicitly "specify" that the value is not going to be used or is only there for side effects. You're not using class field in the definition, but that's okay for -Ywarn-unused.


Your other option is to use silencer plugin to suppress warnings for these few methods.