The Omnipresent Underscore Character
That little character _ (underscore) seems to be everywhere in Scala—you’ve seen it a few times in this book so far; it’s probably the most widely used symbol in Scala. Knowing the different places where it’s used can alleviate surprises when you encounter it the next time. Here’s a list of various uses of the symbol.
The _ symbol may be used:
-
as a wildcard in imports For example, import java.util._ is the Scala equivalent of import java.util.* in Java.
-
as a prefix to index a tuple Given an tuple val names = ("Tom", "Jerry") you can access the two values using the syntax names._1 and names._2, respectively.
-
as implied arguments to a function value The code list.map { _ * 2 } is equivalent to list.map { e ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access