【问题标题】:What is the preferred way to get the first element of a random-access Scala collection获取随机访问 Scala 集合的第一个元素的首选方法是什么
【发布时间】:2016-12-11 21:15:47
【问题描述】:

有两种方法可以获取随机访问 Scala 集合(例如 Vector)的第一个元素:

1) 头部

myCollction.head

2) 申请

myCollction(0)

根据我收集到的信息(来自 Scala 2.10.4 源代码)

  • head首先检查集合是否为空,并在调用apply(0)之前抛出异常

    override /*IterableLike*/ def head: A = {
      if (isEmpty) throw new UnsupportedOperationException("empty.head")
        apply(0)
    }
    
  • apply 先检查索引的边界,在获取元素之前抛出 IndexOutOfBoundsException

    def apply(index: Int): A = {
      val idx = checkRangeConvert(index)
      getElem(idx, idx ^ focus)
    }
    
    private def checkRangeConvert(index: Int) = {
      val idx = index + startIndex
      if (0 <= index && idx < endIndex)
        idx
      else
        throw new IndexOutOfBoundsException(index.toString)
    }
    

首选方式是什么? (实际的好处/陷阱,不是个人喜好)

【问题讨论】:

    标签: scala scala-collections


    【解决方案1】:

    使用 .headOption

    通常首选的方式是(但取决于上下文)

    myCollection.headOption
    

    .headOption 返回 Option 值,其中当 head 存在时 option 为 Some,如果集合为空则为 none。

    使用 headOption 不会抛出异常,因为集合是空的,因此您不会有任何意外的惊喜。

    当基础集合为空时,.head 和零索引都会引发异常。

    这也取决于上下文,如果你想在 head 元素不存在的情况下失败,那么.head 是一个很好的方法,但在很多情况下,如果集合不存在,你想提供一个替代方案里面有任何元素

    【讨论】:

      【解决方案2】:

      我认为选择任何集合的第一个元素的最惯用的方法是使用headOption 方法,该方法在出现异常的情况下返回None。会被抛出。这种方法的好处是调用者可以在headOption 上进行模式匹配并做出适当的响应。

      【讨论】:

        猜你喜欢
        • 2013-09-11
        • 1970-01-01
        • 2011-03-21
        • 1970-01-01
        • 2010-09-12
        • 2021-12-08
        • 2022-01-22
        • 2017-03-11
        • 2011-05-27
        相关资源
        最近更新 更多