在Scala中有两个上限?

时间:2011-03-07 10:43:39

标签: scala types

  

可能重复:
  How do I setup multiple type bounds in 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:基类和特征需要保持分离

1 个答案:

答案 0 :(得分:11)

def workOnNumAttr[T <: Attribute with NumAttr] (attr: T) {
    println (attr.name)
    println (attr.defaultVal)
}