Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 356
Bill Barrington Avatar asked Jan 15 '23 23:01

Bill Barrington


2 Answers

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.

like image 61
Luigi Plinge Avatar answered Jan 20 '23 09:01

Luigi Plinge


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)
like image 45
Plasty Grove Avatar answered Jan 20 '23 09:01

Plasty Grove