_ 必须遵循方法

发布于 2024-10-21 19:18:58 字数 534 浏览 4 评论 0原文

从更复杂的程序简化:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

多孤肩上扛 2024-10-28 19:18:58

在 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 using m _

See Difference between method and function in Scala

魂ガ小子 2024-10-28 19:18:58
scala> def g(func: String => String) = func(_)
g: (func: (String) => String)(String) => String

括号使一切变得不同。这是 _ 绑定的棘手问题之一;它可以用于将方法提升为闭包,也可以用于部分应用程序,但这两种用法并不相同!

scala> def g(func: String => String) = func(_)
g: (func: (String) => String)(String) => String

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!

烟酉 2024-10-28 19:18:58

这就是你想做的吗?

scala> def g(func: T) = func
g: (func: (String) => String)(String) => String

scala> g(f)("test")
res8: String = test (parsed)

is this what you're trying to do?

scala> def g(func: T) = func
g: (func: (String) => String)(String) => String

scala> g(f)("test")
res8: String = test (parsed)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文