In scala, how can i create a general purpose function to perform the following operation:
f: List[A] ==> List[Option[A]]
If you want all elements to be Some(...)
(like you mentioned in your comment) use something like this:
scala> def f[A](in: List[A]): List[Option[A]] = in.map(Some(_))
f: [A](in: List[A])List[Option[A]]
scala> f(0 to 5 toList)
warning: there was one feature warning; re-run with -feature for details
res4: List[Option[Int]] = List(Some(0), Some(1), Some(2), Some(3), Some(4), Some(5))
scala> f(List("a", "b", null))
res5: List[Option[String]] = List(Some(a), Some(b), Some(null))
@2rs2ts's answer would give you:
scala> def f_2rs2ts[A](in: List[A]): List[Option[A]] = in.map(Option.apply)
f_2rs2ts: [A](in: List[A])List[Option[A]]
scala> f_2rs2ts(List("a", "b", null))
res6: List[Option[String]] = List(Some(a), Some(b), None)
Isn't it as simple as
_.map(Option.apply)
?