1
votes

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.

1

1 Answers

3
votes

The errors shown by highlighting in the IntelliJ IDE seem misleading. The real error is recursive functions in the example are missing a return type:

def sum(ints: List[Int]):Int

def product(ds: List[Double]):Double

IntelliJ will show you these errors in the Messages pane once you press the Evaluate worksheet green arrow button.