Scala type mismatch error in for loop

scala, types

Solution

Add `reversed` after the for loop. In Scala the last line in a function is the return value. The `for (i <- list){...}` returns `Unit`.

object Reverse {
  def reverseList(list: List[Int]): List[Int] = {
    var reversed: List[Int] = List()
    for (i <- list) {
      reversed = i :: reversed
    }
    reversed
  }
  def main(args: Array[String]) {
    println(reverseList(List(1,2,3,4)))
  }
}

Problem

I'm trying to write a reverse method in Scala that takes a list and returns the reverse. I have: ``` object Reverse { def reverseList(list: List[Int]): List[Int] = { var reversed: List[Int] = List() for (i <- list) { reversed = i :: reversed } } def main(args: Array[String]) { println(reverseList(List(1,2,3,4))) } } ``` But when I try to compile, I'm getting: ``` example.scala:4: error: type mismatch; found : Unit required: List[Int] for (val i <- list) { ^ ``` The List "list" was declared to be of type List[Int]. Why is it being recognized as type Unit?

Original source