簡體   English   中英

函數 Scala 的返回值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM