func(_) 和 func _ 之间的区别
任何人都可以告诉我 Scala 中 func _ 和 func(_) 之间的区别吗?我必须重写这个方法:
def validations: List[ValueType => List[FieldError]] = Nil
如果我用:重写
val email = new EmailField(this, 255){
override def validations = valUnique _ :: Nil
private def valUnique(email: String): List[FieldError] = {
Nil
}
}
它就可以,而如果我用:重写
val email = new EmailField(this, 255){
override def validations = valUnique(_) :: Nil
private def valUnique(email: String): List[FieldError] = {
Nil
}
}
它就不行。谁能帮我解释一下为什么吗?非常感谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在以下情况下:
您部分应用
valUnique
方法,导致它被装箱为函数。另一方面:
指定用于调用 valUnique 方法的占位符,这通常是为了将匿名函数传递给其他高阶函数,如下所示:
在您的情况下,有尽管部分应用程序仍然完全有效,但范围内没有任何内容可用于满足此类占位符。
请注意,您还可以在将方法作为参数传递之前将其提升为函数:
这种相似性几乎肯定是您感到困惑的原因,即使这两种形式所做的事情不太相同在幕后。
In the case of:
You are partially applying the
valUnique
method, causing it to be boxed as a function.On the other hand:
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: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:
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.
如果你这样写:
我确信它会告诉你你正在得到一个
String =>; List[List[FieldError]]
而不是所需的类型。当使用下划线代替参数(而不是作为表达式的一部分)时,它会在直接外部作用域中扩展为函数。具体来说,另一方面,
valUnique _
只是说“获取这个方法并将其转换为函数”,所以If you wrote it like this:
I'm sure it would tell you you are getting a
String => List[List[FieldError]]
instead of the required type. When an underline is used in place of a parameter (instead of as part of an expression), it is expanded as a function in the immediate outer scope. Specifically,On the other hand,
valUnique _
is just saying "get this method and turn it into a function`, so