I'm just wondering if it is semantically correct to use traits to build game objects. On one hand, I view this as a has a relationship (an object has components), but on the other hand I view components as composing an object.
For example. You have a GameObject. A GameObject does pretty much nothing on its own, but the things you mix into it give it additional properties. Components could be HealthComponent (has health), PhysicsComponent (simulates physics), ClickableComponent (can be clicked).
I like the idea of using traits because all of the properties and methods are added on the original object and I can do player.getHP
instead of player.getHealthComponent.getHP
. On the other hand, I find the naming and semantics of using traits weird. trait HealthComponent extends GameObject
- this doesn't make sense. A HealthComponent
belongs to a GameObject, it doesn't fulfill the is a relationship that's implied by extend
. Am I correct in assuming that traits are normally treated as specialized versions of their parent class? If so, how would I name something like the above object?
To supplement @Moritz's answer, it's also possible to stack related behaviors without inheriting implementation from the super type:
trait HasFoo { def foo: Unit }
class GameObject extends HasFoo {
def foo = {}
}
trait Health extends HasFoo {
self: GameObject =>
abstract override def foo = {
println("health foo")
super.foo
}
}
trait Dog extends HasFoo {
self: GameObject =>
abstract override def foo = {
println("dog foo")
super.foo
}
}
scala> val g = new GameObject with Health with Dog
g: GameObject with Health with Dog = $anon$1@33b7b32c
scala> g.foo
dog foo
health foo
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