I am a beginner to scala and functional programming and trying to learn the fundamentals. For the purpose I've started reading the book Functional Programming In Scala. To start with a set of exercises they've defined a List class (as copied below)
sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A](x: A, xs: List[A]) extends List[A]
object List {
def sum(ints: List[Int]) = ints match {
case Nil => 0
case Cons(x, xs) => x + sum(xs)
}
def product(ds: List[Double]) = ds match {
case Nil => 1.0
case Cons(x, xs) => x * product(xs)
}
def apply[A](as: A*): List[A] =
if (as.isEmpty)
Nil
else Cons(as.head, apply(as.tail: _*))
}
which should work. But when I try to do the same in scala worksheet (IntelliJ plugin), I see error that methods sum
and product
cannot be applied with such function definition(The exact error thrown is Type mismatch, required Byte/Char/Int/Double...., found Any
). So my question is how do I override data structures defined in scala library in a trait/worksheet defined in my package.