Consider rewriting
.find().isDefined
as .exists()
8
9object Utils {
10 def count(arr: Array[Int], criteria: Int => Boolean): Int = arr.filter(criteria).size
11 def exists(arr: Array[Int], criteria: Int => Boolean): Boolean = arr.find(criteria).isDefined12 def filterBy(arr: Array[Int], criteria: Int => Boolean): Array[Int] = arr.filter(criteria)
13 def filterBy(arr: Array[Int], first: Int => Boolean, `then`: Int => Boolean): Array[Int] =
14 arr.filter(first).filter(`then`)
Description
The expression .find(p => ...).isDefined
can be written as .exists(p => ...)
.
Certain Scala collections implement methods such as .find
that selects the first element from a collection which satisfies the specified condition/predicate. This method returns an Option
, i.e. either Some
or None
depending on whether such an element exists or not. Additionally, Option
defines a method called .isDefined
that returns true in case of Some
and false in case of None
. It is therefore suggested that you rewrite the expression .find(p => ...).isDefined
as .exists(p => ...)
for readability and concision.
Bad practice
val userExists = users.find(u => u.email == email).isDefined
Recommended
val userExists = users.exists(u => u.email == email)