Generics in scala for addition -
class calculator[a:numeric]{ var x:a = _; def sum() : = x+x; //error: }
compiler errors:
- can't resolve + symbol on a
- type mismatch; expected: string, actual: a
class calculator[a: numeric]{ ... }
is syntax sugar for
class calculator[a](implicit n: numeric[a]){ ... }
if in the docs numeric
you'll find implicit def mkorderingops
uses "enrich library" pattern add math operators +
a
type.
you need import mkorderingops
instance of numeric
.
keeping current class signature, can use implicitly[numeric[a]]
instance. putting together, get:
class calculator[a: numeric] { private val n = implicitly[numeric[a]] import n._ // mkorderingops included here var a: = _ def sum = + // + coming mkorderingops conversion }
Comments
Post a Comment