Scala泛型类支持多个arities的功能

时间:2011-05-12 22:10:45

标签: scala

假设我有以下类Foo,它使用tupling技巧支持任何arity的函数:

abstract class Foo[T, R] {
  def pull: T => R
}

我可以使用以下语法定义子类:

implicit def function2Tofunction1[T1, T2, R](f: (T1, T2) => R): ((T1, T2)) => R = {
    f.tupled 
}

class Moo extends Foo[(Int, Int), Int] {
  def pullImpl(x: Int, y:Int):Int = x + y
  def pull = (pullImpl _) // implicit converts to tupled form
}

val m = new Moo()
m.pull(4, 5)

这很笨重。理想的语法如下:

class Moo extends Foo[(Int, Int), Int] {
  def pullImpl(x: Int, y:Int):Int = x + y
}

有没有办法定义我的基类,这样才能实现?

1 个答案:

答案 0 :(得分:4)

如果您对将实现定义为函数而不是方法感到满意,那么这可以工作:

abstract class Foo[T, R] {
   type Fn = T => R
   val pull: Fn
}

class Moo extends Foo[(Int, Int), Int] {
   // The type has to be explicit here, or you get an error about
   // an incompatible type. Using a type alias saves typing out
   // the whole type again; i.e. ((Int, Int)) => Int
   lazy val pull: Fn = (x: Int, y: Int) => x + y
}

否则,我认为您需要更多机制来支持不同城市的实施方法签名:

trait Foo[T, R] { 
   type Fn = T => R
   val pull: T => R
} 

trait FooImpl2[T1, T2, R] extends Foo[(T1, T2), R] {
   lazy val pull: Fn = (pullImpl _).tupled
   protected def pullImpl(x: T1, y: T2): R
}

// similarly for FooImpl3, FooImpl4, ...

class Moo extends FooImpl2[Int, Int, Int] {
   protected def pullImpl(x: Int, y: Int) = x + y
}