30

为什么queue.get() 返回空列表?

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())
  }
}

我怎样才能得到第一个元素?

4

2 回答 2

40

它不是返回空列表,而是返回Unit(一个零元组),这是 Scalavoid在 Java 中的等价物。如果它返回空列表,您会看到List()打印到控制台而不是()(空元组)。

问题是您的get方法使用了错误的语法。您需要使用 an=来表示get返回一个值:

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

或者这可能更好:

def get = this.queue.head

在 Scala 中,对于没有副作用的空函数,您通常不使用括号(参数列表),但这要求您在调用时也不要使用括号queue.get

您可能想快速浏览一下Scala Style Guide,特别是关于方法的部分

于 2013-08-25T04:48:21.490 回答
2

有时它可以很好地使用

拿 1

而不是 head 因为它不会导致空列表异常并再次返回一个空列表。

于 2013-08-25T07:43:26.470 回答