【发布时间】:2015-08-15 23:11:03
【问题描述】:
为什么不这个表达式会抛出索引越界异常?
scala> Vector(1,2,3,4).splitAt(50000000)
res2: (Vector(1, 2, 3, 4),Vector())
【问题讨论】:
标签: scala
为什么不这个表达式会抛出索引越界异常?
scala> Vector(1,2,3,4).splitAt(50000000)
res2: (Vector(1, 2, 3, 4),Vector())
【问题讨论】:
标签: scala
来自splitAt的scaladoc:
/** Splits this $coll into two at a given position.
* Note: `c splitAt n` is equivalent to (but possibly more efficient than)
* `(c take n, c drop n)`.
* $orderDependent
*
* @param n the position at which to split.
* @return a pair of ${coll}s consisting of the first `n`
* elements of this $coll, and the other elements.
*/
def splitAt(n: Int): (Repr, Repr)
drop 的 Scaladoc:
/** Selects all elements except first ''n'' ones.
* $orderDependent
* @param n the number of elements to drop from this $coll.
* @return a $coll consisting of all elements of this $coll except the first `n` ones, or else the
* empty $coll, if this $coll has less than `n` elements.
*/
def drop(n: Int): Repr
对于take:
/** Selects first ''n'' elements.
* $orderDependent
* @param n the number of elements to take from this $coll.
* @return a $coll consisting only of the first `n` elements of this $coll,
* or else the whole $coll, if it has less than `n` elements.
*/
def take(n: Int): Repr
如您所见,这些方法旨在不引发任何异常。
【讨论】:
Option 或Either 中的包装结果替换抛出异常。在splitAt 的情况下,可以为任何参数返回合理的结果,而无需更改或包装结果类型。
val v = Vector(1,2,3,4),然后是v(4),结果是java.lang.IndexOutOfBoundsException: 4。为什么在一种情况下这样做而不在其他情况下这样做?