Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between func(_) and func _

Anyone can tell me the difference between func _ and func(_) in Scala? I had to override this method:

def validations: List[ValueType => List[FieldError]] = Nil

If I override it with:

val email = new EmailField(this, 255){
  override def validations = valUnique _ :: Nil
  private def valUnique(email: String): List[FieldError] = {
    Nil
  }
}

It is ok, while if I override it with:

val email = new EmailField(this, 255){
  override def validations = valUnique(_) :: Nil
  private def valUnique(email: String): List[FieldError] = {
    Nil
  }
}

It is not ok. Anyone can me explain why? Thank you very much.

like image 421
Filippo De Luca Avatar asked Dec 16 '22 17:12

Filippo De Luca


1 Answers

In the case of:

valUnique _

You are partially applying the valUnique method, causing it to be boxed as a function.

On the other hand:

valUnique(_)

specifies a placeholder for a call to the valUnique method, which would typically be done in order to pass an anonymous function to some other high order function, as in:

emails flatMap { valUnique(_) }

In your case, there's nothing in scope that could be used to fulfill such a placeholder, though partial application is still completely valid.

Note that you can also lift a method to a function, before passing it as an argument:

emails flatMap { valUnique _ }

This similarity is almost certainly the cause of your confusion, even though these two forms aren't doing quite the same thing behind the scenes.

like image 127
Kevin Wright Avatar answered Jan 10 '23 01:01

Kevin Wright