gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:26:03 31 4
gpt4 key购买 nike

我打了电话 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)将返回一个空集合。

关于scala - 安全地获取数组的尾部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18647874/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com