neel
neel

Reputation: 9061

Return value of Function Scala

I have following program in Scala :

object Ch4 {

        def main(args: Array[String]) {
      println("Hello, world!")
      val x = sortMap()
      println(x)
    }                                             //> main: (args: Array[String])Unit

    def sortMap ( ) {
        val scores = scala.collection.immutable.SortedMap ( "Alice" -> 10, "Fred" -> 7, "Bob" -> 3)
        return scores
    }                                             //> sortMap: ()Unit
}  

I am confused why sortMap function has return type Unit inspite of Map. Also why nothing is getting print in main function.

Upvotes: 0

Views: 1587

Answers (1)

Lee
Lee

Reputation: 144136

Method definitions of the form def name() { ... } implicitly return Unit. You need to add the return type and add an =:

def sortMap(): SortedMap[String, Int] = {
    val scores = scala.collection.immutable.SortedMap ( "Alice" -> 10, "Fred" -> 7, "Bob" -> 3)
    return scores
}

or simply:

def sortMap() = SortedMap("Alice" -> 10, "Fred" -> 7, "Bob" -> 3)

Upvotes: 1

Related Questions