I'm trying to get the hang of Scala traits and case classes. Below is a followup to this question.
Suppose I have a simple class and an object that extends it.
sealed trait Operations{
def add(a:Double,b:Double):Double
def multiply(a:Double,b:Double):Double
}
case object CorrectOperations extends Operations{
def add(a:Double,b:Double):Double = a+b
def multiply(a:Double,b:Double):Double= a*b
}
Now I have some function that will make use of any object of type Operations
, such as,
def doOperations(a:Double,b:Double, op:Operations)={ op.multiply(a,b) - op.add(a,b)}.
This works well, but my question is how to generalize the types of trait Operations
, so we're not just talking about Doubles
. So i'd like to have generic types for trait Operations
and then type specification for each object.
Using type generics, I tried
sealed trait Operations[T]{
def add(a:T,b:T):T
def multiply(a:T,b:T):T
}
case object CorrectOperations extends Operations[Double]{
def add(a:Double,b:Double):Double = a+b
def multiply(a:Double,b:Double):Double= a*b
}
def doOperations[T](a:T,b:T, op:Operations[T])={ op.multiply(a,b) - op.add(a,b) },
with a compile error at doOperations
- "value - is not a member of type parameter T".
So we know that op.multiply(a,b)
will return type T
, and the error would indicate that type T
has no .-
method.
How should I be thinking about achieving this generalization of trait Operations
? Thanks