Search code examples
scalacompiler-warningsimplicitsuppress-warnings

Suppress unused warnings in a particular scope


In Scala (2.12) when writing a trait I have added a default implementation that can be overridden by some subclasses. Since throughout my entire implementation the state is required almost everywhere it's implicit such that I don't have to pass it every time it's required.

Considering the following code snippet, the compiler does complain that the implicit parameter state of SomeTrait.defaultMethod remains unused and throws an error. Is there any option to suppress this kind of error in that particular scope? I definitely want to keep the unused errors globally.

trait SomeTrait {

  def defaultMethod(implicit state: State) : Unit = {
     // default implemenation does nothing
  }
}

class Subclass extends SomeTrait{

 override def deafultMethod(implicit state: State) : Unit = {
    state.addInformation()
 }
}

Also, I would like to keep the state implicit. In theory, it's possible to add a fake usage to the method but that's not a clean solution.


Solution

  • Scala 2.13 introduced @unused annotation

    This annotation is useful for suppressing warnings under -Xlint. (#7623)

    Here are few examples

    // scalac: -Xfatal-warnings -Ywarn-unused
    
    import annotation.unused
    
    class X {
      def f(@unused x: Int) = 42       // no warn
    
      def control(x: Int) = 42         // warn to verify control
    
      private class C                  // warn
      @unused private class D          // no warn
    
      private val Some(y) = Option(42) // warn
      @unused private val Some(z) = Option(42) // no warn
    
      @unused("not updated") private var i = 42       // no warn
      def g = i
    
      @unused("not read") private var j = 42       // no warn
      def update() = j = 17
    }