Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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'

like image 675
Manu Chadha Avatar asked Sep 14 '25 07:09

Manu Chadha


1 Answers

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
like image 60
Jean Logeart Avatar answered Sep 16 '25 05:09

Jean Logeart