斯卡拉。获取 List 的第一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18425771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 02:04:05  来源:igfitidea点击:

Scala. Get first element of List

scalalist

提问by user2009490

Why does queue.get() return empty list?

为什么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())
  }
}

How i can get first element?

我如何获得第一个元素?

回答by DaoWen

It's not returning the empty list, it's returning Unit(a zero-tuple), which is Scala's equivalent of voidin Java. If it were returning the empty list you'd see List()printed to the console rather than the ()(nullary tuple).

它不是返回空列表,而是返回Unit(一个零元组),这与voidJava 中的Scala 等效。如果它返回空列表,您会看到List()打印到控制台而不是()(空元组)。

The problem is you're using the wrong syntax for your getmethod. You need to use an =to indicate that getreturns a value:

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

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

Or this is probably even better:

或者这可能更好:

def get = this.queue.head

In Scala you usually leave off the parentheses (parameter list) for nullary functions that have no side-effects, but this requires you to leave the parentheses off when you call queue.getas well.

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

You might want to take a quick look over the Scala Style Guide, specifically the section on methods.

您可能想快速浏览一下Scala 风格指南,特别是关于方法部分

回答by hendrik

Sometimes it can be good to use

有时用起来会很好

take 1

取 1

instead of head because it doesnt cause an exception on empty lists and returns again an empty list.

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