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?
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
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With