Scala collect Option

To use the collect function in Scala, you need something list-like. This can be a real list, or an Option, which is like a list, but it only has one or zero items.

Collect works a lot like map. In this case, we’ll take items from a list, and compute the length of each:

val convertFn: PartialFunction[Any, Int] = { 
  case s: String => s.length; 
  case Some(s: String) => s.length
}

We can call this on an Option, and get results we’d expect:

Option("12345").collect(
  convertFn
)

res14: Option[Int] = Some(5)

If we call it on None, we get None back:

None.collect(convertFn)
res23: Option[Int] = None

If you call this on a list, it works great:

List(
  Option("aaa"),
  Option("bb"),
  None
).collect(
  convertFn
)

res25: List[Int] = List(3, 2)

And, this works great, because it removes all the Nones.

Leave a Reply

Your email address will not be published. Required fields are marked *