3
votes

I'm trying to define a generic add function to numeric values:

def add[A](x:A, y:A): A = {
  x + y
}


console:16: error: type mismatch; found : A required: String x + y ^

What's the compiler complaining about? Some of the stuff I've googled does not quite make sense to me at this moment.

2
You have explicitly told the compiler that you have a method that takes two arguments with types that you know nothing about (except that they are the same type). Since you explicitly said to the compiler that you know nothing about the types, you also cannot know that they have a + method.Jörg W Mittag
Possible duplicate of Type parameter in scalaJörg W Mittag

2 Answers

10
votes

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)
}
2
votes

To be able to do something like this the compiler needs to know that A has a method

def +(a: A): A

so ideally you would want to do something like

def add[A :< Numeric](x:A, y:A): A = { ... 

but you can't because the numeric types in Scala have no common super type (they extend AnyVal). Look here for a related question.