我打电话tail给Array,但看到了一个警告.
scala> val arr = Array(1,2)
arr: Array[Int] = Array(1, 2)
scala> arr tail
warning: there were 1 feature warning(s); re-run with -feature for details
res3: Array[Int] = Array(2)
Run Code Online (Sandbox Code Playgroud)
Scaladocs for Array显示了一个UnsupportedOperationException [will be thrown]
if the mutable indexed sequence is empty.
是否存在安全,不会抛出异常,获取数组尾部的方法?
Mar*_*amy 13
是否存在安全,不会抛出异常,获取数组尾部的方法?
你可以使用drop:
scala> Array(1, 2, 3).drop(1)
res0: Array[Int] = Array(2, 3)
scala> Array[Int]().drop(1)
res1: Array[Int] = Array()
Run Code Online (Sandbox Code Playgroud)
另请注意,正如@TravisBrown在下面的注释中所提到的,drop不区分空尾(对于具有一个元素的集合)和缺少尾(对于空集合),因为在这两种情况下,drop(1)将返回空集合.
首先,警告与您使用不安全方法的事实无关.如果您重新启动REPL,-feature您将看到以下内容:
scala> arr tail
<console>:9: warning: postfix operator tail should be enabled
by making the implicit value language.postfixOps visible...
Run Code Online (Sandbox Code Playgroud)
和指向文档的scala.language.postfixOps,它包括以下注意事项:
后缀运算符与分号推断的交互性很差.大多数程序员因此而避免使用它们.
这是个好建议.能够写arr tail而不是arr.tail不值得大惊小怪.
现在关于安全问题.标准库不提供tailOption集合,但您可以使用headOption和获得相同的效果map:
scala> val arr = Array(1, 2)
arr: Array[Int] = Array(1, 2)
scala> arr.headOption.map(_ => arr.tail)
res0: Option[Array[Int]] = Some([I@359be9fb)
Run Code Online (Sandbox Code Playgroud)
如果这对您来说过于冗长或不透明或效率低下,您可以轻松创建一个隐式类,tailOption以便为Array(或Seq,或IndexedSeq等)添加更好的内容.