【发布时间】:2018-09-19 11:46:05
【问题描述】:
似乎有三种(或更多)方法可以限制哪些类可以混入给定的 scala 特征:
- 使用共同祖先 [特征]
- 使用抽象声明
- 在特质中使用自我类型
共同祖先方法需要额外的限制,而且似乎不是最理想的。同时,自键入和抽象声明似乎是相同的。有人愿意解释区别和用例(尤其是在 2 和 3 之间)吗?
我的例子是:
val exampleMap = Map("one" -> 1, "two" -> 2)
class PropsBox (val properties : Map[String, Any])
// Using Common Ancestor
trait HasProperties {
val properties : Map[String, Any]
}
trait KeysAsSupertype extends HasProperties {
def keys : Iterable[String] = properties.keys
}
class SubProp(val properties : Map[String, Any]) extends HasProperties
val inCommonAncestor = new SubProp(exampleMap) with KeysAsSupertype
println(inCommonAncestor.keys)
// prints: Set(one, two)
// Using Abstract Declaration
trait KeysAsAbstract {
def properties : Map[String, Any]
def keys : Iterable[String] = properties.keys
}
val inAbstract = new PropsBox(exampleMap) with KeysAsAbstract
println(inSelfType.keys)
// prints: Set(one, two)
// Using Self-type
trait KeysAsSelfType {
this : PropsBox =>
def keys : Iterable[String] = properties.keys
}
val inSelfType = new PropsBox(exampleMap) with KeysAsSelfType
println(inSelfType.keys)
// prints: Set(one, two)
【问题讨论】:
标签: scala inheritance traits self-type