The Scala collections all define the find
function. The find operation traverses a collection and returns the first item in the collection that meets the given condition(s).
Perhaps you are a teacher. You have a type that represents a student with a name and a grade:
case class Student(name: String, grade: Int)
And you have a randomized list of those students:
val students = List( Student("Sally", 79), Student("Giedrius", 81), Student("Aryana", 98), Student("Ty", 94), Student("Eloise", 86), Student("Vergil", 89), Student("Doug", 66), Student("Delmar", 77), Student("Makenna", 88), Student("Orval", 93) )
Maybe you want to reward a random A-student (i.e., a student with a grade of 90 or above) with a candy bar. You can use find
to return the first A-student in the list:
val scholar = students.find(_.grade >= 90) // scholar: Option[Student] = // Some(Student(Aryana,98))
So, that’s great: Aryana gets a Twix! (It is the only one with the cookie crunch, after all.)
Notice, by the way, that scholar
is not a Student
, but rather an Option
that contains a Student
. Let’s get back to that in a minute.
You also happen to be one of those sadistic teachers, though, who likes to embarrass the students who are not living up to their potential. Therefore you pick a random F-student (i.e., with a grade less than 65) and outfit him/her with a dunce cap:
val dunce = students.find(_.grade < 65) // dunce: Option[Student] = None
Isn’t that interesting? There are no F-students. (Who’s the dunce now?)
That’s the beauty of find
: it returns an Option
instead of the bare Student
. Therefore if no item in the list meets find
’s predicate, it does not throw an exception or return null
(the way some other languages do). It just returns None
. That way, if you write something like this in which you specify that you expect the Student
type, Scala does not let you get away with it:
val dunce: Student = students.find(_.grade < 65) // error: type mismatch; // found : Option[Student] // required: Student // val dunce: Student = students.find(_.grade < 65) // ^
It warns you at compile time that you are aiming a firearm at your foot instead of letting you shoot it off at run time with one exception or another.
It could be that you give a test next week that slays the entire class: you may not have an A-student that week. The Option
value that find
returns makes you test dunce
and scholar
before you use them to make sure someone is supposed to get a candy bar or a dunce cap before you start handing them out.