I’m learning scala, and this question may be stupid, but… why?
For example, this is ok:
def matchList(ls: List[Int]): List[Int] = ls match {
case 1 :: rest => rest
case a :: b :: rest => (a + b) :: rest
case _ => ls
}
matchList: (ls: List[Int])List[Int]
But function with type parameter does not compile:
def matchList[T](ls: List[T]): List[T] = ls match {
case 1 :: rest => rest
case a :: b :: rest => (a + b) :: rest
case _ => ls
}
<console>:10: error: type mismatch;
found : T
required: String
case a :: b :: rest => (a + b) :: rest
Why?
For any type
Tthe operationT + Tdoesn’t make any sense. (Do all types support+? No. Think of adding two dogs or two employees.)In your case, the string concatenation operator is getting invoked (added via
any2stringaddpimp), whose return type is (obviously)String. Hence the error message.What you need is a way to specify that type
Tmust support an operation where you combine two values of typeTto yield a new value of typeT. Scalaz‘sSemigroupfits the bill perfectly.The following works: