2013-08-25 83 views
17

爲什麼queue.get()返回empy列表?斯卡拉。獲取列表的第一個元素

class MyQueue{ 
    var queue=List[Int](3,5,7) 

    def get(){ 
    this.queue.head 
    } 
} 

object QueueOperator { 
    def main(args: Array[String]) { 
    val queue=new MyQueue 
    println(queue.get()) 
    } 
} 

我如何得到第一個元素?

+3

在您學習時,您可能會發現明確寫出超出必需類型的數據是很有用的。在這種情況下,如果你編寫了'def get():Int {this.queue.head}',編譯器會告訴你get方法有問題。 –

回答

24

它沒有返回空列表,它返回Unit(零元組),這是Scala在Java中的void的等效值。如果它返回空列表,你會看到List()打印到控制檯而不是()(空數據元組)。

問題是你使用錯誤的語法爲你的get方法。您需要使用一個=,表明get返回值:

def get() = { 
    this.queue.head 
} 

或者這可能是更好的:

def get = this.queue.head 

在Scala中,你通常會離開關閉無參函數括號(參數列表)沒有任何副作用,但這需要您在撥打queue.get時也不要使用括號。

您可能想要快速查看Scala Style Guide,特別是section on methods

+3

由於存在這樣的錯誤,我們正在討論關於棄用過程語法'def proc(...){...}'以支持完整形式的def proc(...):Unit = {...} 。參見https://groups.google.com/forum/?fromgroups=#!topic/scala-debate/8G3WgfZNj9E – ghik

2

有時它可以很好的使用

取1

,而不是頭,因爲它不造成空列表異常並再次返回一個空列表。

+7

'headOption'更好,因爲它不使用任何魔術常量(1),並且它返回一個類型('Option [T]'),靜態保證其最大大小爲1。 –

相關問題