Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala type mismatch error in for loop

Tags:

types

scala

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?

like image 796
user1789874 Avatar asked Oct 31 '12 22:10

user1789874


1 Answers

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)))
  }
}
like image 66
Brian Avatar answered Oct 29 '22 22:10

Brian