开发者

Having two upper bounds in Scala? [duplicate]

This question already has an answer here: Closed 11 years ago.

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 e开发者_JS百科xtends 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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜