Tizianoreica
Tizianoreica

Reputation: 2236

Companion Object override few methods of a trait

So. Assume we have a trait Animal

trait Animal {
  val typeAnimal: String
  val name: String
}

And now I want to create a class Dog, that extends this trait. But I want to use the Companion Object to override the typeAnimal to Mammal, instead to do it on the class Dog itself. Something like

class Dog(override val name: String) extends Animal
object Dog {
  override val typeAnimal = "Mammal"
}

This doesn't work. It raises an error saying to me:

  1. class Dog doesn't implement typeAnimal
  2. the override of typeAnimal on the companion object does not override anything

Is it even possible? Does it have make sense what I'm trying to achieve?

EDIT I assume it's not possible to achieve what I'm trying here following Jorg's comment.

What I was trying to do is: a trait define some static value that each class should implement, like typeAnimal, and, since this belongs to all the instance of each class that implements this trait (e.g. Dog is a mammal, so I don't see any reason why the typeAnimal should be a instance variable instead of a static one) I would like to override in the companion object

Upvotes: 2

Views: 589

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170745

If you want typeAnimal to be "static", it shouldn't be a member of the trait itself. You can do this instead:

trait Animal {
  val name: String
  def companion: AnimalCompanion
  // optional: def typeAnimal = companion.typeAnimal
}

trait AnimalCompanion {
  val typeAnimal: String
}

class Dog(override val name: String) extends Animal {
  override def companion = Dog
}
object Dog extends AnimalCompanion {
  override val typeAnimal = "Mammal"
}

The standard library does that with collections.

Upvotes: 6

Related Questions