typeclass - scala value is not a member of type parameter -
i'm trying hang of scala traits , case classes. below followup this question.
suppose have simple class , object 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 have function make use of 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, question how generalize types of trait operations, we're not talking doubles. i'd have generic types trait operations , type specification each object.
using type generics, 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 compile error @ dooperations - "value - not member of type parameter t".
so know op.multiply(a,b) return type t, , error indicate type t has no .- method.
how should thinking achieving generalization of trait operations ? thanks
in context of problem, should introduce subtract method operations trait, can provide evidence t has such method (well doesn't, method subtraction t another).
sealed trait operations[t] { def add(a: t, b: t): t def multiply(a: t, b: t): t def subtract(a: t, b: t): t } case object correctoperations extends operations[double]{ def add(a: double, b: double): double = + b def multiply(a: double, b: double): double = * b def subtract(a: double, b: double): double = - b } def dooperations[t](a: t, b: t, op: operations[t]) = op.subtract(op.multiply(a,b), op.add(a,b)) this numeric trait does.
Comments
Post a Comment