如何从 Scala 集合中的索引中获取选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16231254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:13:49 来源:igfitidea点击:
How to get an Option from index in Collection in Scala?
提问by Loic
Is there a way, only using the Scala collection API, to get an Option in a List when trying to get an element by its index?
在尝试通过索引获取元素时,有没有办法仅使用 Scala 集合 API 来获取列表中的选项?
I'm looking for the equivalent of this function, does it exist?
我正在寻找这个函数的等价物,它存在吗?
def optionalValue[T](l: List[T], index: Int) = {
if (l.size < (index+1)) None
else Some(l(index))
}
Thanks
谢谢
回答by drexin
Yes, you can lift your collection to a function Int => Option[A]:
是的,您可以将您的收藏提升为一个函数Int => Option[A]:
scala> List(1,2,3).lift
res0: Int => Option[Int] = <function1>
scala> List(1,2,3).lift(9)
res1: Option[Int] = None

