Why can't _ be used to indicate an unused / ignored argument in a method override?

Consider:

trait Validation { def isValid(str: String): Boolean } class AlwaysValid extends Validation { override def isValid(_: String) = true } 

gives

 <console>:1: error: identifier expected but '_' found. override def isValid(_: String) = true 

Any ideas why? Or is it just what language designers missed?


Maybe this concerns passing the argument name, but this only applies to non-overrides, since in any case it overrides auto- "inherit" the argument names from the overridden method, so this may not be the case:

 trait Foo { def bar(arg0: String): String } class Baz extends Foo { override def bar(blabla: String) = "hello" } new Baz().bar(arg0 = "world") // works, even though the arg name is blabla in Baz 

Also: _ allowed in lambdas, even several times:

 scala> val x: Int => Int = _ => 3 x: Int => Int = <function1> scala> val x: (Int, Int) => Int = (_, _) => 3 x: (Int, Int) => Int = <function2> 
+7
scala
source share
3 answers

Because you can use parameter names when calling a method.

Scala allows you to change the parameter name when overriding (although not recommended), but you always need to specify the caller name if they want to.

+6
source share

Here is a slightly more detailed explanation of what is happening:

  • the reason _ works with lambdas is because lambdas can never have named arguments.
  • in the case of polymorphic calls to instances of a subclass ( Baz ) through references of the type of the parent class ( Foo ), Scala simply β€œinherits” the method names of the parent class ( arg0 ) into the subclass so polymorphic calls do not see the changed name blabla in Baz#bar ;
  • however, the subclass method must still be called directly, so it needs to be given valid names for its arguments, so _ will not work for obvious reasons; he also recommended that they match the method names of the parent class, which were overridden for reasons of clarity.
+3
source share

I think this is just a grammar problem.

_ is a special identifier in scala and can be used in a well-defined set of cases, such as lambdas, a partial method application, and pattern matching.

I did not consider the language specification, but it is safe to assume that the method parameter should be the identifier of the name, and _ simply invalid.

+2
source share

All Articles