Search code examples
scalafoldleft

Expression of type B => List[B] doesn’t conform to expected type List[Int] when reverse a list in Scala


Working on a function to reverse a list in Scala using the foldLeft function:

def reverseWithFold(ls: List[Int]): List[Int] =
        ls.foldLeft(List[Int]())((c, _) => _:::c)

it got compiling errors: Expression of type List[B_] => List[Int] doesn’t comforrm to expected type List[Int] (PS: I know my solution is not correct)

Can I know what does it mean? In _:::c here, the _ represents the c in (c, _), and c is a List[Int] type, so in my opinion, _:::c should be the concatenation of two List[Int]. It should conform with the expected type, right?


Solution

  • Underscores are not valid variable names, they are used to ignore variables. The two underscores in (c, _) and _ ::: c are unrelated.

    • (c, _) => { ... } ignores the second parameter completely, it's gone.
    • _ ::: c is a shortcut for the lambda expression x => x ::: c, which expects an x that is a List[B_] for some unknown type B_ that cannot be inferred, because it's not expected, and it's nowhere to be found in your code.

    If you wanted to prepend the second argument to the first, you would have to write something like

    ls.foldLeft(List.empty[Int])((c, x) => x :: c)
    

    or even

    ls.foldLeft(List.empty[Int])(_.::(_))