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:

res14: Option[Int] = Some(5)

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

res23: Option[Int] = None

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

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

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

Interested in Scala? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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