Categories
Tech

Scala Saturday — The exists Method

The Scala collections API defines the exists method on all its classes. The exists method takes a predicate. If any item in the collection meets the predicate, exists returns true. Otherwise, it returns false.

List(1, 3, 5, 7, 9) exists { _ == 3 }
// res0: Boolean = true

(1 to 12) exists { _ < 1 }
// res1: Boolean = false

Array(1, 3, 5, 7, 9) exists { _ % 3 == 0 }
// res2: Boolean = true

Set(1, 3, 5, 7, 9) exists { _ % 2 == 0 }
// res3: Boolean = false

Strings are collections/sequences of characters, so both of the following are valid:

"asdf" exists { _ == 's' }
// res4: Boolean = true

"asdf" exists { _ == 'b' }
// res5: Boolean = false

The Map module also defines an exists function, but the predicate takes two inputs: one for the key and one for the value.

val m = Map("A" -> 1, "B" -> 2, "C" -> 4, "D" -> 8)
m exists { _ == "D" -> 8 }
// res6: Boolean = true

And of course, if you want to test only the key or only the value, only test the first field or the second field, respectively, of the input tuple.

m exists { _._1 == "Z" }
// res7: Boolean = false

m exists { _._2 == 2 }
// res8: Boolean = true

Option also defines an exists method. If the option is Some, then exists applies the predicate to the value in the Some instance and returns the result. If the option is None, then exists always returns false (as the REPL is kind enough to point out to us).

Some("X") exists { _ == "X" }
// res9: Boolean = true

Some("X") exists { _ == "Y" }
// res10: Boolean = false

None exists { _ == "X" }
// <console>:8: warning:
// comparing values of types
// Nothing and String using
// `==' will always yield false
//      None exists { _ == "X" }
//                      ^
// res11: Boolean = false

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.