获取随机访问 Scala 集合的第一个元素的首选方法是什么
What is the preferred way to get the first element of a random-access Scala collection
有两种方法可以获取随机访问 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)
}
首选方式是什么? (实际的好处/陷阱,不是个人喜好)
使用.headOption
通常首选的方式是(但这取决于上下文)
myCollection.headOption
.headOption
returns 选项值,当 head 存在时选项为 Some,如果集合为空则为 none。
使用 headOption 不会在集合为空时抛出异常,因此您不会有任何意想不到的惊喜。
当基础集合为空时,.head
和零索引都会抛出异常。
这也取决于上下文,如果你想在 head 元素不存在时失败,那么 .head
是一个很好的方法,但很多情况下你想提供如果集合中没有任何元素,则为替代方案
我认为 select 任何集合(包括 Vector
等随机访问集合)的第一个元素的最惯用方法是使用 headOption
方法returns None
在会抛出异常的情况下。这种方法的好处是调用者可以在 headOption
上进行模式匹配并做出适当的响应。
有两种方法可以获取随机访问 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) }
首选方式是什么? (实际的好处/陷阱,不是个人喜好)
使用.headOption
通常首选的方式是(但这取决于上下文)
myCollection.headOption
.headOption
returns 选项值,当 head 存在时选项为 Some,如果集合为空则为 none。
使用 headOption 不会在集合为空时抛出异常,因此您不会有任何意想不到的惊喜。
当基础集合为空时,.head
和零索引都会抛出异常。
这也取决于上下文,如果你想在 head 元素不存在时失败,那么 .head
是一个很好的方法,但很多情况下你想提供如果集合中没有任何元素,则为替代方案
我认为 select 任何集合(包括 Vector
等随机访问集合)的第一个元素的最惯用方法是使用 headOption
方法returns None
在会抛出异常的情况下。这种方法的好处是调用者可以在 headOption
上进行模式匹配并做出适当的响应。