如何为Scala中的值分配实例方法?

时间:2012-03-16 21:33:17

标签: scala

相关:How do you assign a function to a value in Scala?

鉴于:

class Foo{
  def bar = println("bar")
  def bat = println("bat")
}

如何创建fnRef,使其指向Foo.barFoo.bat

def deepFunction(foos : List[Foo], fnRef : ()=>Unit) = {
  foos.map(_.fnRef) //May call either bar or bat
}  

额外奖励:是否可以约束fnRef,使其成为Foo类中该签名的唯一方法?

3 个答案:

答案 0 :(得分:6)

你没有。 :-)而是用一流函数编写代码。 Scala的优点在于它将创建_.method的函数文字,其类型为T => R,其中T是参数的类型,而R是方法的返回类型。

因此,_.bar_.bat都会Foo => Unit

scala> class Foo{
     |   def bar = println("bar")
     |   def bat = println("bat")
     | }
defined class Foo

scala> def deepFunction(foos: List[Foo], fn: Foo => Unit) {
     |   foos.map(fn)
     | }
deepFunction: (foos: List[Foo], fn: Foo => Unit)Unit

scala> deepFunction(List(new Foo, new Foo), _.bar)
bar
bar

scala> deepFunction(List(new Foo, new Foo), _.bat)
bat
bat

这种方法的真正好处在于你可以使用你想要的任何功能,而不仅仅是成员函数。

scala> def bam(f: Foo) { println("bam") }
bam: (f: Foo)Unit

scala> deepFunction(List(new Foo, new Foo), bam)
bam
bam    

答案 1 :(得分:2)

您可以通过部分应用程序获取对方法的引用:

scala> val foo = new Foo
foo: Foo = Foo@5dc22e67

scala> val fun = foo.bar _
fun: () => Unit = <function0>

scala> fun()
bar

这也适用于多个参数列表:

scala> class Bar { def bar(s: String, t: String) = println(s+t) }
defined class Bar

scala> new Bar().bar _
res0: (String, String) => Unit = <function2>

答案 2 :(得分:1)

方法不是Scala中的对象,您不能将它们分配给名称。

相关问题