Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having two upper bounds in Scala? [duplicate]

Tags:

types

scala

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

like image 812
stephanos Avatar asked Dec 13 '22 15:12

stephanos


1 Answers

def workOnNumAttr[T <: Attribute with NumAttr] (attr: T) {
    println (attr.name)
    println (attr.defaultVal)
}
like image 150
Martin Ring Avatar answered Jan 06 '23 06:01

Martin Ring