Jea*_*let 9 pointers scala function
假设我在Scala中有一个简单的类:
class Simple {
def doit(a: String): Int = 42
}
Run Code Online (Sandbox Code Playgroud)
我如何在一个val中存储带有两个参数的Function2 [Simple,String,Int](目标Simple对象,String参数),并且可以调用doit()来获取结果吗?
sep*_*p2k 14
val f: Function2[Simple, String, Int] = _.doit(_)
Run Code Online (Sandbox Code Playgroud)
hba*_*sta 12
与sepp2k相同,只是使用另一种语法
val f = (s:Simple, str:String) => s.doit(str)
Run Code Online (Sandbox Code Playgroud)
对于那些不喜欢打字类型的人:
scala> val f = (_: Simple).doit _
f: (Simple) => (String) => Int = <function1>
Run Code Online (Sandbox Code Playgroud)
遵循_为任何arity工作的方法:
scala> trait Complex {
| def doit(a: String, b: Int): Boolean
| }
defined trait Complex
scala> val f = (_: Complex).doit _
f: (Complex) => (String, Int) => Boolean = <function1>
Run Code Online (Sandbox Code Playgroud)
这包括§6.23"匿名函数的占位符语法"和Scala参考的 §7.1"方法值"的组合.