Function 如何从Scala中的方法获取函数对象?

Function 如何从Scala中的方法获取函数对象?,function,scala,pointers,Function,Scala,Pointers,假设我在Scala中有一个简单的类: class Simple { def doit(a: String): Int = 42 } 如何在val中存储接受两个参数(目标简单对象,字符串参数)的函数2[Simple,String,Int],并调用doit()返回结果?与sepp2k相同,只是使用另一种语法而已 val f: Function2[Simple, String, Int] = _.doit(_) val f = (s:Simple, str:String) => s.do

假设我在Scala中有一个简单的类:

class Simple {
  def doit(a: String): Int = 42
}

如何在val中存储接受两个参数(目标简单对象,字符串参数)的函数2[Simple,String,Int],并调用doit()返回结果?

与sepp2k相同,只是使用另一种语法而已

val f: Function2[Simple, String, Int] = _.doit(_)
val f = (s:Simple, str:String) => s.doit(str)

对于那些不喜欢打字的人:

scala> val f = (_: Simple).doit _
f: (Simple) => (String) => Int = <function1>

这包括在§6.23“匿名函数的占位符语法”和§7.1“方法值”(称为“部分应用程序”)的组合中。如图所示,这是一个特例。顾名思义,部分应用程序中可能会提供一些参数,结果函数具有arity N-M,其中N是原始方法(或函数)的arity,M是部分应用程序中固定的参数数。我想知道编译器如何判断doit方法是否真的存在;我看到显式键入在这里起作用。谢谢使用类型为(简单)=>(字符串)=>Int的函数与类型为(简单,字符串)=>Int的函数的实际含义是什么?我知道前者用f(obj)(“str”)调用,后者用f(obj,“str”)调用,前者返回另一个函数对象,如果只是用一个参数列表调用它:f(obj)。但是,在创建对象的数量和方法调用的数量方面,幕后会发生什么呢?创建了两个Function1对象而不是一个Function2对象,并具有额外的间接级别。
scala> trait Complex {                        
     |    def doit(a: String, b: Int): Boolean
     | }                                      
defined trait Complex

scala> val f = (_: Complex).doit _            
f: (Complex) => (String, Int) => Boolean = <function1>