Scala foldRight type mismatch

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) 

The Scala compiler complains 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?

+4
source share
2 answers

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

+7
source

What Luigi says works for me. I'm not sure why you need a type parameter, since you already specify the input as an Int list:

 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 the side and not related to the actual question, if this is the intended result, an alternative way could be:

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

Source: https://habr.com/ru/post/1447122/


All Articles