Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing values returned from scala function

object TestClass {
  def main (args: Array[String]) {
    println("Hello World");
    val c = List (1,2,3,4,5,6,7,8,9,10)
    println(findMax(c))
  }
  def findMax (tempratures: List[Int]) {
    tempratures.foldLeft(Integer.MIN_VALUE) {Math.max}
  }
}

Output shown is

Hello World 
()

Why is the output not

Hello World
10

I'm doing this in IntelliJ

like image 493
Omnipresent Avatar asked Dec 03 '22 06:12

Omnipresent


2 Answers

This is one of the most common scala typos.

You're missing the = at the end of your method:

def findMax (tempratures: List[Int]) {

Should read:

def findMax (tempratures: List[Int]) = {

Leaving the = off means that your method returns Unit (nothing).

like image 200
Pablo Fernandez Avatar answered Dec 05 '22 19:12

Pablo Fernandez


Because you define findMax without return type, so the return type is Unit or ().

def findMax (tempratures: List[Int]) { ... }

aka

def findMax (tempratures: List[Int]) : Unit = { ... }

You want instead

def findMax (tempratures: List[Int]) : Int = { ... }

or with omitted type

def findMax (tempratures: List[Int]) = { ... }
like image 27
0__ Avatar answered Dec 05 '22 18:12

0__