[英]Return value of Function Scala
我在 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
}
我很困惑為什么sortMap
函數具有返回類型Unit
sortMap
Map
。 還有為什么在main
函數中沒有print
任何內容。
def name() { ... }
形式的方法定義隱式返回Unit
。 您需要添加返回類型並添加一個=
:
def sortMap(): SortedMap[String, Int] = {
val scores = scala.collection.immutable.SortedMap ( "Alice" -> 10, "Fred" -> 7, "Bob" -> 3)
return scores
}
或者干脆:
def sortMap() = SortedMap("Alice" -> 10, "Fred" -> 7, "Bob" -> 3)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.