The difference between func (_) and func _

Can anyone 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 redefine it with:

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

This is normal if I redefine it:

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

It is not normal. Can anyone explain to me why? Thank you very much.

+4
source share
2 answers

If you wrote it like this:

 override def validations: List[ValueType => List[FieldError]] = valUnique(_) :: Nil 

I am sure this will tell you that you are getting String => List[List[FieldError]] instead of the required type. When an underscore is used in place of a parameter (and not as part of an expression), it expands as a function in the immediate external area. In particular,

 valUnique(_) :: Nil // is translated into x => valUnique(x) :: Nil (valUnique(_)) :: Nil // would be translated into (x => valUnique(x)) :: Nil // which would be correct 

valUnique _ , valUnique _ other hand, simply says: “Get this method and turn it into a function,” so

 valUnique _ :: Nil // gets translated into (x => valUnique(x)) :: Nil 
+4
source

When:

 valUnique _ 

You partially apply the valUnique method, forcing it to be inserted as a function.

On the other hand:

 valUnique(_) 

indicates a placeholder for calling the valUnique method, which is usually executed in order to pass an anonymous function to some other high-order function, for example:

 emails flatMap { valUnique(_) } 

In your case, there is nothing that could be used to execute such a placeholder, although a partial application is still completely valid.

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

 emails flatMap { valUnique _ } 

This similarity is almost certainly the cause of your confusion, although the two forms are not exactly the same behind the scenes.

+8
source

Source: https://habr.com/ru/post/1340593/


All Articles