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 makeAnimal(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.
In Scala, an abstract class is constructed using the abstract keyword. It contains both abstract and non-abstract methods and cannot support multiple inheritances. A class can extend only one abstract class. The abstract methods of abstract class are those methods which do not contain any implementation.
In Scala, an object of a class is created using the new keyword. The syntax of creating object in Scala is: Syntax: var obj = new Dog();
To implement Scala abstract class, we use the keyword 'abstract' against its declaration. It is also mandatory for a child to implement all abstract methods of the parent class. We can also use traits to implement abstraction; we will see that later.
Scala traits don't allow constructor parameters However, be aware that a class can extend only one abstract class.
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 = ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With