Syntax error naming function parameter _

in Scala 2.13 is it allowed to name a function parameter _ to denote that the value is unused?

For example, the following function triggers compiler errors and IntelliJ errors.

  def prog2[A,B,C](_:A, val2:B, code2: => C):B = {
    code2 // eval for side effect

The errors are

identifier expected but '_' found.
  def prog2[A,B,C](_:A, val2:B, code2: => C):B = {

Why do you ask for a value if you are not going to use it?
Or are you overriding the method from a parent class?

How am I supposed to name a function parameter which is unused?

Hi Luis, this and several other functions are simply part of my Common Lisp compatibility library.
prog2 is simply a 3-ary function which returns the 2nd given value. the 1st argument is evaluated for side-effect at the call-site.

I still do not understand why you ask for a parameter that you won’t use.

But in any case, the answer is no, there is no way to name an argument that won’t be used.
Because, except when overriding, that is considered as a potential bug.

for the purpose of the question, you can imagine that it is a method which has 3 arguments in the parent class, or it is one of a set of functions which all need to have the same calling semantics for some reason.

I think you can annotate it @unused, but that should only make a difference if unused warnings are enabled. You’ll still have to name it though.

1 Like

What’s the syntax for @unused ? I didn’t see the syntax in the linked documentation.

scala> def foo(@unused a: String, b: String) = b
def foo(a: String, b: String): String

scala> def foo(a: String, b: String) = b
       warning: parameter value a in method foo is never used
def foo(a: String, b: String): String
1 Like

unfortunately IntelliJ still flags it as a warning. :face_vomiting:

@SuppressWarnings("unused") usually takes care of IntelliJ.

1 Like

Thanks for the suggestion, @charpov. Sadly, I don’t see how to use this though.

For example, I’ve updated my code as follows, but IntellJ now gives a different error.

  def prog2[A,B,C](@unused _unused : A, val2:B, code2: => C):B = {
    code2 // eval for side effect
type mismatch;
 found   : String("unused")
 required: Array[String]
  def prog2[A,B,C](@SuppressWarnings("unused") @unused _unused : A, val2:B, code2: => C):B = {

My mistake. This is something I use in Java, not Scala.
@nowarn("cat=unused") is the Scala one.

@charpov, can you please give me an example of how to write the function using this syntax? Does the annotation precede the function definition, or is it somehow embedded within the definition?

class Foo {
  //noinspection ScalaUnusedSymbol
  def hook(arg: Int) = ()

This seems to take care of IntelliJ. I use @nowarn to silence warnings from the Scala compiler, but I’m not getting any on the unused argument anyway.

This could be related to the compiler options I’ve added to the build.sbt file ???

scalacOptions ++= Seq(