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 T
the operation T + T
doesn'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 any2stringadd
pimp), whose return type is (obviously) String
. Hence the error message.
What you need is a way to specify that type T
must support an operation where you combine two values of type T
to yield a new value of type T
. Scalaz's Semigroup
fits the bill perfectly.
The following works:
def matchList[T : Semigroup](ls: List[T]): List[T] = ls match {
case 1 :: rest => rest
case a :: b :: rest => (a |+| b) :: rest // |+| is a generic 'combining' operator
case _ => ls
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With