zaxme zaxme - 1 year ago 59
Scala Question

Scala provide type information in subclassed generic function

Here is my problem.

I have an abstract class that defines a method with type parameters as input and output. I want the subclasses to provide the type information when subclassing but I want to do it in a way that I don't parametrize the whole class.

Some pseudo code of what I'm aiming at.

abstract class A {
def foo[T](t: T): T

class B() extends A {
override foo[Int](t: Int): Int = t + 1

class C() extends A {
override foo[Double](t: Double): Double = t + 1.0

How do I pass the type information on subclassing? I looked at similar problems. They address that with self types, type classes and abstract types.


Answer Source

As you've said, an abstract type on A can solve that:

abstract class A {
  type T
  def foo(t: T): T

class B extends A {
  override type T = Int
  override def foo(t: Int): Int = t + 1

class C extends A {
  override type T = Double
  override def foo(t: Double): Double = t + 1.0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download