How do you declare the values ​​and methods of an abstract object in scala?

I want to indicate the color of animals once, and it is the same for all animals of the same species.

So, I would like to:

abstract object Animal {val color: String}

And then specify individual animal colors with

object Dog extends Animal {val color = "green"}

This should be in the object, since I already have an agreement that cannot be changed only so that animals can be declared in the Animal object using the factory method, and the factory methods need access to the color. eg.

abstract object Animal {
   val color: String
   def makeAnimal(args): Animal = ...
}

How do I actually do this in scala, given that "only classes can declare, but undefined members"?

I can think of a hacky way to do this with the hell, but I hope there is something better.

[EDIT] , , / . , , . .

+5
1

object s . , , :

trait AnimalCompanion {
  val color: String
  def makeAnimal(args): Animal // if you have same args everywhere
}

object Dog extends AnimalCompanion {
  val color = ...
  def makeAnimal(args) = ...
}

trait AnimalCompanion[A <: Animal] {
  val color: String
  def makeAnimal(args): A
}

class Dog extends Animal

object Dog extends AnimalCompanion[Dog] {
  val color = ...
  def makeAnimal(args): Dog = ...
}
+15

All Articles