Scala _ [underscore] magic
29 Mar 2010I started learning Scala a few days before. Initially i was annoyed by
the use of too many symbols in Scala. Especially i was confused by the
_
and its different meaning in different places. After a few days of
research(aka search), i felt better and i started to love its
syntax. Ok, lets see the usage of _
in Scala.
Pattern Matching
In Scala, pattern matching is somewhat similar to java switch statement. But it is more powerful.
In Scala, each selector will be matched with the patterns in the order
they appear and the first match will be executed. _
acts like a
wildcard. It will match anything. Scala allows nested patterns, so we
can nest the _
also.Lets see another example that uses _
in nested
pattern.
Anonymous Functions
Scala represents
anonymous functions with a
elegant syntax. The _
acts as a placeholder for parameters in the
anonymous function. The _
should be used only once, But we can use
two or more underscores to refer different parameters.
Here the _ refers to the parameter. The first one is a short form of the second one. Lets look at another example which take two parameters.
There is a good post which explains the inner details of the above example.
import
In scala, _
acts similar to *
in java while importing packages.
Properties
In scala, a getter and setter will be implicitly defined for all
non-private var in a object. The getter name is same as the variable
name and _=
is added for setter name. We can define our own getters
and setters. This is looking similar to Ruby getters and setters. Ok
lets see an example which uses the getter and setters.
Functions
Scala is a functional language. So we can treat function as a normal
variable. If you try to assign a function to a new variable, the
function will be invoked and the result will be assigned to the
variable. This confusion occurs due to the optional braces for method
invocation. We should use _
after the function name to assign it to
another variable.