I want to create a method sum that I can call on different types, specifically sum(1,2).
def sum[A](a1: A, a2: A) = a1 + a2
This fails because the compiler can’t tell if A has a method ‘+’
I tried to define a structural type:
type Addable = {def +(a: Addable)}
This fails because of an illegal cyclic reference
How can I achieve this in a type safe way without requiring A to extend a specific trait?
Scala does not support recursive type aliases without additional compiler arguments (specifically,
-Yrecursion). This is partially to keep the type checker at least somewhat in the realm of decidability (though, as we have discovered, the type system is Turing Complete even without recursive type aliases, so it doesn’t much matter).The correct way to do this sort of thing is with a typeclass. Scala encodes these as implicit view bounds. For example:
And of course, this also allows you to do fancy things like sum the contents of a
Seqin a type-safe manner:It is worth noting that Scala 2.8 has something very close to this with the
Numerictypeclass.