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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.