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 => e * 2 }. Likewise, the code list.reduce { _ + _ } is equivalent to list.reduce { (a, b) => a + b }.

  • to initialize variables with default values For example, var min : Int = _ initializes min to 0 while var msg : String = _ initializes the variable msg to null.

  • to mix operators in function names As you’ll recall, in Scala operators are defined as methods; for example, the :: method that’s used to prefix an element to a list. Scala does not permit directly mixing operators with alphanumeric characters; for example, foo: is not allowed. However, you may use an underscore to get around that restriction, like so: foo_:.

  • as a wildcard in pattern matching case _ will match any value given whereas case _: Int will match any integer value. Furthermore, case <people>{_*}</people> will match an XML element named people with zero or more children.

  • with case in the catch block, when handling exceptions.

  • as part of the explosion operation, for example, max(arg: _*) to transform an array or list argument to discrete values before passing to a function that expects a varargs.

  • for partially applying a function For example, in the code val square = Math.pow(_: Int, 2) we’ve partially applied the pow method to create a square function.

The _ symbol is intended to make the code concise and expressive. Use your judgement when deciding when to make use of that symbol. Use it only when the code truly appears concise—that is,the code is transparent and easy to understand and maintain. Avoid it if you feel the code is getting to be terse, hard to understand, or cryptic.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.64.126