【发布时间】:2010-07-13 15:00:18
【问题描述】:
假设我在 Scala 中有一个简单的类:
class Simple {
def doit(a: String): Int = 42
}
如何将 Function2[Simple, String, Int] 存储在一个 val 中,它接受两个参数(目标 Simple 对象,String 参数),并且可以调用 doit() 让我返回结果?
【问题讨论】:
假设我在 Scala 中有一个简单的类:
class Simple {
def doit(a: String): Int = 42
}
如何将 Function2[Simple, String, Int] 存储在一个 val 中,它接受两个参数(目标 Simple 对象,String 参数),并且可以调用 doit() 让我返回结果?
【问题讨论】:
val f: Function2[Simple, String, Int] = _.doit(_)
【讨论】:
与 sepp2k 相同,只是使用了另一种语法
val f = (s:Simple, str:String) => s.doit(str)
【讨论】:
对于那些不喜欢打字的人:
scala> val f = (_: Simple).doit _
f: (Simple) => (String) => Int = <function1>
遵循_ 的方法适用于任何数量:
scala> trait Complex {
| def doit(a: String, b: Int): Boolean
| }
defined trait Complex
scala> val f = (_: Complex).doit _
f: (Complex) => (String, Int) => Boolean = <function1>
Scala Reference 的第 6.23 节“匿名函数的占位符语法”和第 7.1 节“方法值”的组合涵盖了这一点
【讨论】: