0
votes

I would like to create a generic allowing me to reuse some functions for mutliple classes. Ideally my design would be:

class ColoredMesh[T <: Mesh] extends T
{
  def Color(color:ColorRGBA) = {
    val vertices = super.getVertexCount
    // do something
  }
}

class ColoredSphere extends ColoredMesh[Sphere]

class ColoredCylinder extends ColoredMesh[Cylinder]

However, this gives compile errors:

Error:(7, 38) class type required but T found

class ColoredMesh[T <: Mesh] extends T

Similar Java question Generic class to derive from its generic type parameter resulted in an answer deriving from a generic type parameter is not possible for technical reasons. I guess this applies for Scala as well. Is there some other common design pattern how to solve this?

2
Type parameter is useless there, it's meant to express inheritance, as seens in @gzm0 answer.cchantep

2 Answers

1
votes

You can use traits and mix-in composition:

trait ColoredMesh extends Mesh {
  def Color(color:ColorRGBA) = {
    val vertices = super.getVertexCount
    // do something
  }
}

class ColoredSphere extends Sphere with ColoredMesh
1
votes

You can define a trait with a self-type:

trait Colored { self: Mesh =>
    def Color(color: ColorRGBA) = {
        self.getVertexCount
        //do something
    }
}

class ColoredSphere extends Sphere with Colored