如何在Scala中将类方法作为参数传递

Mik*_*ley 11 scala

假设我有一些C类方法

def class C {
  def f1():Int = ...
  def f2():Int = ...
}
Run Code Online (Sandbox Code Playgroud)

现在我想要一个带有两个C实例的方法,以及一个C方法,但我不知道f1,f2的类型是什么,也不知道如何调用它们.我觉得它看起来像

def cmp(first:C, second:C, t:() => Int): Boolean = {
  first.t < second.t
}
Run Code Online (Sandbox Code Playgroud)

这抱怨说t不是C的方法.当然必须有办法表达这一点.

ghi*_*hik 12

def cmp(first:C, second:C, t: C => Int): Boolean = {
  t(first) < t(second)
}
Run Code Online (Sandbox Code Playgroud)

然后...

val c1 = new C
val c2 = new C
cmp(c1, c2, _.f1())
cmp(c1, c2, _.f2())
Run Code Online (Sandbox Code Playgroud)

这是使用匿名函数.最后两行相当于:

cmp(c1, c2, {c: C => c.f1()})
cmp(c1, c2, {c: C => c.f2()})
Run Code Online (Sandbox Code Playgroud)

除非使用某种反射,否则不能传递对方法的引用.

  • 其实两个答案都很好 - 谢谢!但我接受了这个,因为它是我实际使用的那个. (2认同)

mik*_*łak 9

您只需传递方法引用:

object DoOperation extends App {

  class C(val x: Int) {
      def f1():Int = x-1
      def f2():Int = x+1
   }


  def cmp(first: () => Int, second: () => Int): Boolean = {
    first() < second()
  }

  override def main(args: Array[String]) {
      println(cmp(new C(1).f1,new C(0).f2)) //prints "true"
      println(cmp(new C(1).f2,new C(1).f1)) //prints "false"
  }

}
Run Code Online (Sandbox Code Playgroud)

这些方法将在相应的对象实例上关闭,因此净效果等同于您想要完成的效果.