Bill Barrington
Bill Barrington

Reputation: 188

Puzzling Type Mismatch in Scala foldRight

Can someone please tell me what is wrong with this function definition?

def incr[Int](l: List[Int]): List[Int] = 
  l.foldRight(List[Int]())((x,z) => (x+1) :: z)

Scala compiler is complaining about type mismatch in the body of the function passed to foldRight:

<console>:8: error: type mismatch;
 found   : Int(1)
 required: String
           l.foldRight(List[Int]())((x,z) => (x+1) :: z)
                                                ^

What is the problem here?

Upvotes: 4

Views: 280

Answers (2)

Plasty Grove
Plasty Grove

Reputation: 2887

What Luigi says works for me. I'm not sure why you would want the type parameter since you're already specifying the input as a List of Int:

def incr(l: List[Int]): List[Int] = l.foldRight(List[Int]())((x,z) => (x+1) :: z)

incr(List(1,2,3))                 //> res0: List[Int] = List(2, 3, 4)

But on a sidenote and not related to the actual question, if that's the intended outcome, an alternative way could be:

def incr2(l:List[Int]):List[Int] = l map (_+1)

Upvotes: 2

Luigi Plinge
Luigi Plinge

Reputation: 51109

With def incr[Int] you've defined an arbitrary type with the name Int, which overrides the existing one. Get rid of the [Int] type parameter and it works fine, or use a different name like T.

Upvotes: 7

Related Questions