collect vs collectFirst - why the return values are of different type - Scala

The question is to confirm if I have correctly understood the use of Option.

I notice that method collect returns a List while collectFirst returns an Option. Is it because collect can return multiple values or none (none being represented by an empty list). collectFirst on other hand returns a single value (or nothing) and thus it makes more to use an Option as we will never return a 'list'

5

1 Answer

You are right:

scala> (1 to 5).collect { case i if i % 2 == 0 => "*" * i }
res: scala.collection.immutable.IndexedSeq[String] = Vector(**, ****)
scala> (1 to 5).collectFirst { case i if i % 2 == 0 => "*" * i }
res: Option[String] = Some(**)
scala> (1 to 5).collect { case i if i > 10 == 0 => "*" * i }
res: scala.collection.immutable.IndexedSeq[String] = Vector()
scala> (1 to 5).collectFirst { case i if i > 10 == 0 => "*" * i }
res: Option[String] = None

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like