简单的 Scala 代码:从字符串数组中返回第一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15074580/
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-10-22 05:00:24  来源:igfitidea点击:

Simple scala code: Returning first element from string array

scala

提问by kr85

I don't know how to fix this code. It "explodes" somewhere in returnFirstStringbut I don't know why. Also, I don't know how to properly display result using println. Is this approach ok.

我不知道如何修复此代码。它在returnFirstString 的某处“爆炸”,但我不知道为什么。另外,我不知道如何使用println正确显示结果。这个方法可以吗。

So here's the code:

所以这是代码:

def returnFirstString(a: Array[String]): Option[String]=
{
    if(a.isEmpty) { None }
    Some(a(0))
}
val emptyArrayOfStrings = Array.empty[String]
println(returnFirstString(emptyArrayOfStrings))

回答by Noah

You're not properly returning the None:

您没有正确返回 None:

  def returnFirstString(a: Array[String]): Option[String] = {
    if (a.isEmpty) {
      None
    }
    else {
      Some(a(0))
    }
  }

Also, there's already a method for this on most scala collections:

此外,在大多数 Scala 集合中已经有一个方法:

emptyArrayOfStrings.headOption

回答by pedrofurla

The most concise way:

最简洁的方法:

def returnFirstString(a: Array[String]): Option[String]= a.headOption