IT干货网

scala之安全地获取数组的尾部

Renyi-Fan 2025年12月25日 编程设计 39 0

我打了电话 tailArray 上,但看到了警告。

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) 

Scaladocs Array显示 UnsupportedOperationException [will be thrown] if the mutable indexed sequence is empty.
有没有安全的,不会抛出异常的方法来获取数组的尾部?

请您参考如下方法:

Is there a safe, won't throw exception, way to get the tail of an array?



您可以使用 drop :
scala> Array(1, 2, 3).drop(1) 
res0: Array[Int] = Array(2, 3) 
 
scala> Array[Int]().drop(1) 
res1: Array[Int] = Array() 

另请注意,如 @TravisBrown 所述在下面的评论中, drop不区分空尾(对于具有一个元素的集合)和没有尾(对于空集合),因为在这两种情况下, drop(1)将返回一个空集合。


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!