bsky
bsky

Reputation: 20242

Found Unit, required Int

I have the following Scala code:

object Solution {

    def getBestSolution(sumList: List[Int]): Int = {
        return 0
    }

    def main(args: Array[String]) {
        val t = readInt()

        (0 until t).foreach({
            val n = readInt()
            val a = readLine().split(" ").map(_.toInt).toList
            val sumList = a.scanLeft(0)(_ + _).tail.toList
            //println(classOf[sumList])
            println(sumList)
            println(getBestSolution(sumList)) 
        })
    }

}

For it, I am getting this error:

file.scala:16: error: type mismatch;
 found   : Unit
 required: Int => ?
            println(getBestSolution(sumList))
                   ^
one error found

Any idea what is causing this?

Upvotes: 0

Views: 2406

Answers (2)

Ramesh Maharjan
Ramesh Maharjan

Reputation: 41987

you could have done it with simple for comprehension too instead of foreach

  for(x <- 0 to t){
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt).toList
    val sumList = a.scanLeft(0)(_ + _).tail.toList
    //println(classOf[sumList])
    println(sumList)
    println(getBestSolution(sumList))
  }

To sum up, Programming in Scala book has pointed that Scala provides the for comprehension, which provides syntactically pleasing nesting of map, flatMap, and filter ... The for comprehension is not a looping construct, but is a syntactic construct the compiler reduces to map, flatMap, and filter.

Upvotes: 1

Dima
Dima

Reputation: 40510

The argument you are passing to foreach is the result of executing the code block (which is a Unit), not a function. Remove the outer parentheses (they do not really hurt anything, but are unnecessary and look ugly), and add _ => in the beginning:

(0 to t).foreach { _ => 
   ...
   println(getBestSolution(sumList))
}

This is the proper syntax for creating an unnamed function. The stuff before => is the parameter list that the function accepts. In your case, you can just put an underscore there, because you do not need the value of the parameter. Or you could give it a name if you needed to do something with it, e.g.: (0 to t).foreach { x => println(x*x) }

Upvotes: 4

Related Questions