I am a scala noob, learning through functional programming in scala book. i was doing some exercises, and this thing really startled me:
def plusone[Int](l: List[Int]): List[Int] = foldRight(l, Nil:List[Int])((x,xs)=>Cons(x+1,xs))
This is a function that would create a new list with ones added to each elements, but when I wrote this, I got this error:
type mismatch; found : Int(1) required: String List.scala /exercises/src/main/scala/fpinscala/datastructures line 94 Scala Problem
Funny thing is, when I removed that [Int]from my function declaration(so just def plusone, and all others stayed same) I didn't have any error. I am at a loss how to understand this, I would appreciate any help you guys can give me.
FYI, some functions I am using there: sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
def foldRight[A,B](as: List[A], z: B)(f: (A, B) => B): B =
as match {
case Nil => z
case Cons(x, xs) => f(x, foldRight(xs, z)(f))
}
All others should be generic, I believe.
Let's review the syntax using your examples:
def foldRight[A,B](as: List[A], z: B)(f: (A, B) => B): B = ...
def plusone[Int](l: List[Int]): List[Int] = ...
def plusone(l: List[Int]): List[Int] = ...
Do you see the difference? Think about it a little bit.
So, what happened is that def xxx[X]
means make X
a type variable. In the case where it wasn't working the type of your list wasn't List[scala.Int]
, it was a list for some type unknown at the declaration of plusone, Int
, that shadowed scala.Int
. And that's why it was complaining about the x+1
.
The reason for this specific error lies the Predef.any2stringadd
implicit conversion that "augments" all types with a method def +(String)
.