开发者

Having two upper bounds in Scala? [duplicate]

开发者 https://www.devze.com 2023-02-15 10:40 出处:网络
This question already has an answer here: Closed 11 years ago. Possible Duplicate: How do I setup multiple type bounds in Scala?
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

精彩评论

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