I want to specify an animals color once, and it is the same for all animals of the same species.
So I'd like to do:
abstract object Animal {val color: String}
And then specify individual animals colors with
object Dog extends Animal {val color = "green"}
This needs to be in the object, as I already have a convention which cannot be changed of only making animals with the factory method also declared in the Animal object, and the factory methods needs access to the color. e.g.
abstract object Animal {
val color: String
def makeAni开发者_JAVA百科mal(args): Animal = ...
}
How do I actually do this in scala, given that "only classes can have declared but undefined members"?
I can think of a hacky way to do this using traits, but I'm hoping there is something better.
[EDIT] So it turns out I can't use traits to hold the values/methods for complicated reasons. The current solution involves staticly registering the child object with the parent object using a trait, and that allows me to access the non-trait values and methods which must be defined in an object. I'm still hoping for a better solution.
You can't extend object
s, by definition. So yes, you need a trait, but I don't see anything hacky about this:
trait AnimalCompanion {
val color: String
def makeAnimal(args): Animal // if you have same args everywhere
}
object Dog extends AnimalCompanion {
val color = ...
def makeAnimal(args) = ...
}
or even better
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 = ...
}
精彩评论