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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With