2

In Scala, I want to have the following traits and classes

trait Paper {
    def paint(args: Material): Unit
}

class WhitePaper extends Paper {
    override def paint(args: DarkMaterial): Unit = {
        darkMaterials.open()
    }
}


trait Material {
   def open() : Unit = {}
}

class DarkMaterial extends Material{
   override def open() : Unit = {
       print("Dark material")
   }
}

However, my IDE shows error for the override of method paint(args: DarkMaterial), even though DarkMaterial extends Material. Why is this wrong? Anyone knows how to fix it?

Thank you so much.

3
  • 2
    paint(DarkMaterial) does not override paint(Material), because paint(Material) can accept any Material; but paint(DarkMaterial) can only accept DarkMaterial. Commented Jul 27, 2016 at 18:36
  • Thx! But how can I fix it so that def paint(args: DarkMaterial) is acceptable? Commented Jul 27, 2016 at 18:53
  • Well, it's not an override. That's why you're getting the error. Whatever you're trying to do, this isn't it. Either paint() is supposed to accept any Material, or it isn't. Commented Jul 27, 2016 at 18:56

1 Answer 1

1

You could use type parameters to nail things down.

trait Paper[M] {
  def paint(args: M): Unit
}

class WhitePaper extends Paper[DarkMaterial] {
  override def paint(args: DarkMaterial): Unit = { // "override" not needed
    args.open()
  }
}
// Material and DarkMaterial are unchanged
Sign up to request clarification or add additional context in comments.

2 Comments

We might want to consider making that [M <: Material] to indicate that the M type is intended to be a material, so you don't end up with a Paper[String], depending on the use cases, of course.
@IanMcLaird Thanks! Your suggestion is very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.