user1789874
user1789874

Reputation: 75

Scala type mismatch error in for loop

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?

Upvotes: 7

Views: 7854

Answers (1)

Brian
Brian

Reputation: 20295

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)))
  }
}

Upvotes: 6

Related Questions