【问题标题】:Splitting At An Index Greater Than The Size Of A Vector在大于向量大小的索引处拆分
【发布时间】:2015-08-15 23:11:03
【问题描述】:

为什么不这个表达式会抛出索引越界异常?

scala> Vector(1,2,3,4).splitAt(50000000)
res2: (Vector(1, 2, 3, 4),Vector())

【问题讨论】:

    标签: scala


    【解决方案1】:

    来自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
    

    如您所见,这些方法旨在不引发任何异常。

    【讨论】:

    • 按照 Java 标准,不抛出异常看起来很奇怪,但出于某种原因,我更喜欢这种方式。
    • 我能想到的不抛出的唯一原因是他们希望保留一些引用透明感,从而保持函数的纯度。
    • @I.K.这是一种更“scala”的方式来避免在“普通”情况下抛出异常。您通常用Option 或Either 中的包装结果替换抛出异常。在splitAt 的情况下,可以为任何参数返回合理的结果,而无需更改或包装结果类型。
    • @I.K. - 大多数高阶集合方法的原则是尽可能做好工作,而不是将非严格需要的细节的错误检查与您的应用程序逻辑混为一谈。大多数时候,如果你尽可能地做最明智的事情,整个事情就会顺利进行,而不必担心边界问题。由于库是为你做的,通过明智,一整类恼人的错误消失了。 (相反出现的类,重要的是即使你不使用它,集合也很大,相比之下它很小。)
    • @RexKerr,是的,敏感性确实会出现,但正如你所知,在现实世界中,编程失误确实会发生。虽然有点矛盾。考虑一下:val v = Vector(1,2,3,4),然后是v(4),结果是java.lang.IndexOutOfBoundsException: 4。为什么在一种情况下这样做而不在其他情况下这样做?
    猜你喜欢
    • 1970-01-01
    • 2013-07-01
    • 2021-07-15
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 2022-07-22
    • 1970-01-01
    相关资源
    最近更新 更多