0

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.

4
  • 3
    You need to use def sortMap ( ) = { ... } Commented Jun 29, 2015 at 11:25
  • After changing it, I am getting this error "method sortMap has return statement; needs result type" Commented Jun 29, 2015 at 11:31
  • Error is removed but still nothing is getting printed in main function in Scala worksheet Commented Jun 29, 2015 at 11:34
  • Well, then add a return type or do not use the return statement, as suggested by the error. Frankly, you could perhaps read at least some basic tutorial or introduction on Scala before seeking help. Commented Jun 29, 2015 at 11:34

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

What I read in documentation is that we don't have to tell the return type of functions in Scala. Only for recursive functions return type is compulsory. Then why is it necessary here?
@neel - It's because you're using an explicit return, see this question. Explicit returns are rarely needed in scala.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.