Scala 有两个上限吗?
可能的重复:
如何在 Scala 中设置多个类型边界?
我对 Scala 的类型系统有点困惑。我有与此类似的类型:
// ==== BASE CLASS
class Attribute {
def name(): String
def defaultVal(): Any
}
// ==== TRAIT - defines data type of an attribute
trait AttributeDataType[T] {
def defaultVal(): T
}
trait TextAttr extends AttributeDataType[String] {
def defaultVal() = ""
}
trait NumAttr extends AttributeDataType[Double] {
def defaultVal() = 0.0
}
// ==== CONCRETE ATTRIBUTES
class AgeAttribute extends Attribute with NumAttr {
def name() = "Age"
}
class ColorAttribute extends Attribute with TextAttr {
def name() = "Color"
}
现在应该可以工作:
object Main {
def main(args:Array[String]) {
Main.workOnNumAttr(new AgeAttribute) // SHOULD COMPILE
//Main.workOnNumAttr(new ColorAttribute) // SHOULD NOT COMPILE
}
def workOnNumAttr[T <: [???] (attr: T) { // requires Attribute AND NumAttr
println (attr.name)
println (attr.defaultVal)
}
}
我该怎么做?
PS:基类和特征需要保持分离
Possible Duplicate:
How do I setup multiple type bounds in Scala?
I'm a little stuck on Scala's type system. I have types similar to this:
// ==== BASE CLASS
class Attribute {
def name(): String
def defaultVal(): Any
}
// ==== TRAIT - defines data type of an attribute
trait AttributeDataType[T] {
def defaultVal(): T
}
trait TextAttr extends AttributeDataType[String] {
def defaultVal() = ""
}
trait NumAttr extends AttributeDataType[Double] {
def defaultVal() = 0.0
}
// ==== CONCRETE ATTRIBUTES
class AgeAttribute extends Attribute with NumAttr {
def name() = "Age"
}
class ColorAttribute extends Attribute with TextAttr {
def name() = "Color"
}
And now this should work:
object Main {
def main(args:Array[String]) {
Main.workOnNumAttr(new AgeAttribute) // SHOULD COMPILE
//Main.workOnNumAttr(new ColorAttribute) // SHOULD NOT COMPILE
}
def workOnNumAttr[T <: [???] (attr: T) { // requires Attribute AND NumAttr
println (attr.name)
println (attr.defaultVal)
}
}
How do I do this ?
PS: the base class and the trait need to stay separate
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)