2

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.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
M. Reif
  • 866
  • 7
  • 20
  • 3
    If the default implementation does nothing and it is intended to always be overriden, why not leave it abstract? - If you are in `2.13` you can use the **@Unused** _annotation_., you can `val _ = state` in the implementation, or you can add this helper: `def void(args: Any*): Unit = ((), args)._1` which you can use to discard any unused like `void(foo, bar)` - Finally, an implicit global mutable state sounds like a really bad idea. – Luis Miguel Mejía Suárez Feb 19 '20 at 11:56
  • Mmh thanks, that might help. No worries, the state here is not global. – M. Reif Feb 19 '20 at 12:04

1 Answers1

3

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
}
Mario Galic
  • 47,285
  • 6
  • 56
  • 98