4

Suppose I have the following class Foo, that supports a function of any arity using the tupling trick:

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

I can define a subclass with the following syntax:

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)

This is pretty clunky. The ideal syntax would be as follows:

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

Is there any way to define my base class such that this can be achieved?

Pandora Lee
  • 1,435
  • 2
  • 14
  • 17

1 Answers1

4

If you can be satisfied with defining the implementation as a function rather than a method, then this works:

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
}

Otherwise, I think you'll need more machinery to support implementation method signatures for different arities:

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
}
Aaron Novstrup
  • 20,967
  • 7
  • 70
  • 108