如何从 Scala 集合中的索引中获取选项? [英] How to get an Option from index in Collection in Scala?

查看:45
本文介绍了如何从 Scala 集合中的索引中获取选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试通过索引获取元素时,有没有办法仅使用 Scala 集合 API 来获取列表中的选项?

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?

我正在寻找这个函数的等价物,它存在吗?

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))
}

谢谢

推荐答案

是的,你可以将你的集合提升为一个函数 Int =>选项[A]:

Yes, you can lift your collection to a function 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

这篇关于如何从 Scala 集合中的索引中获取选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆