_ 必须遵循方法
从更复杂的程序简化:
scala> type T = (String) => String
defined type alias T
scala> def f(s: String) = s + " (parsed)"
f: (s: String)java.lang.String
scala> f _
res0: (String) => java.lang.String = <function1>
scala> def g(func: T) = func _
<console>:6: error: _ must follow method; cannot follow (String) => String
def g(func: T) = func _
^
我真的不明白为什么这不起作用。方法和 (Type1, Type2 ...) => 形式的东西有什么区别?输入
,从类似的东西中获取函数部分的正确方法是什么?
Simplified, from a more complex program:
scala> type T = (String) => String
defined type alias T
scala> def f(s: String) = s + " (parsed)"
f: (s: String)java.lang.String
scala> f _
res0: (String) => java.lang.String = <function1>
scala> def g(func: T) = func _
<console>:6: error: _ must follow method; cannot follow (String) => String
def g(func: T) = func _
^
I don't really understand why this doesn't work. What is the difference between a method and something in the form of (Type1, Type2 ...) => Type
, and what's the right way of getting the function partial from something like that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Scala 中,方法和函数之间是有区别的。方法总是属于对象,但函数是对象。方法
m
可以使用m _
转换为函数,请参阅 Scala 中方法和函数的区别
In Scala there is a difference between methods and functions. Methods always belong to an object, but functions are objects. A method
m
can be converted into a function usingm _
See Difference between method and function in Scala
括号使一切变得不同。这是 _ 绑定的棘手问题之一;它可以用于将方法提升为闭包,也可以用于部分应用程序,但这两种用法并不相同!
Parenthesis make all the difference. This is one of the tricky things about the binding of _; it can be used to lift a method to a closure, and it can be used for partial application, but the two usages are not the same!
这就是你想做的吗?
is this what you're trying to do?
我想你正在寻找这个: http:// jim-mcbeath.blogspot.com/2009/05/scala-functions-vs-methods.html
I think you're looking for this: http://jim-mcbeath.blogspot.com/2009/05/scala-functions-vs-methods.html