Since you define A
with no boundaries and no extra information, it could be any type, and not any Scala type has a +
method - so this can't compile.
The error message is a result of the compiler's attempt to implicitly convert x
into a String (because String has a +
method, and every type can be converted to string using toString
), but then it fails because y
isn't a string.
To create a method for all numeric types, you can use the Numeric
type:
def add[A](x:A, y:A)(implicit n: Numeric[A]): A = {
n.plus(x, y)
}
add(1, 3)
add(1.4, 3.5)
EDIT: or an equivalent syntax:
def add[A: Numeric](x:A, y:A): A = {
implicitly[Numeric[A]].plus(x, y)
}