【发布时间】:2016-04-13 01:25:23
【问题描述】:
假设我有一个基本的实体特征
trait Entity {
final val id: Long = IdGenerator.next()
def position: (Double, Double)
}
然后可以通过一些额外的(仍然是抽象的)功能进行扩展
sealed trait Humanoid { self: Entity =>
def health: Double
def name: String
}
最后,有一些具体的案例类与功能混合在一起。
case class Human(
position: (Double, Double),
health: Double,
name: String
)
extends Entity with Humanoid {
}
有了这个,假设我需要定义 Event trait,它封装了从一个实体到另一个实体的一些动作
sealed trait Event[A, B] {
final val timestamp: Long = System.currentTimeMillis
def from: A
def to: B
def event: B => B
}
现在,一些通用事件有一个案例类,它只适用于人形实体。
case class TakeDamage[A <: Entity, B <: Humanoid](damage: Int, from: A, to: B)
extends Event[A,B] {
val event = (ent: B) => {
//a copy of ent with some parameters changed, e.g. health
}
}
这应该是可能的,因为 Humanoid 超类型的所有实体都将具有所需的字段(健康)。
在没有太多样板代码的情况下,在 scala 中是否有任何类型安全且不可变的方法?还是我的抽象完全错误?
【问题讨论】:
标签: scala generics types polymorphism