Danyson
3 min readJul 9, 2020

--

Interesting_Usages_ of_UNDERSCORE _in_SCALA

“ While learning Scala i came through _ underscore symbol and found initialy hard to understand its syntax but when i found its usage ,i realy amazed how handy it is and how helpful in easing a solution using Scala. ”

1.Pattern Matching

The pattern matching is similar to “Switch case” in any language but bit more powerful in case of usage.

Fig 1 : Usage of _ in Pattern matching example I

You see, we have defined the matchTest Method to accept “any data type” as input value and as return value. In Scala, each selector will be matched with the patterns in the order they appear and the first match will be executed. Underscore acts like a wildcard. It will match anything. Similar to the default statement in other languages but still it is simple and handy than default statement. If you replace the “case 1” with “case _” then whatever the input may be, the match feature will invoke the “case _” only.

Let’s see an another example on pattern matching with nested underscore.

Fig 2 : Usage of _ in Pattern matching example II

2.Anonymous Functions

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.

List(1,2,3,4,5).foreach(print(_))

List(1,2,3,4,5).foreach( a => print(a))

what we see here is ,the underscore refers to the parameter. The first one which prints the numbers in List object is a short form of the second one. Lets look at another example which take two parameters.

val sum_A = List(1,2,3,4,5).reduceLeft(_+_)

output : 15

val sum_B = List(1,2,3,4,5).reduceLeft((a, b) => a + b)

output : 15

As you see the first one in sum_A is the short form for the second .The reduceLeft method takes an associative binary operator function as parameter and will use it to collapse elements from the collection. The order for traversing the elements in the collection is from left to right and hence the name reduceLeft.

3. import

In scala, _ acts similar like * in java, while importing packages.

// imports all the classes in the package control
import scala.util.control._

// imports all the members of the object MyFunction.
// (like static import in java)
import com.test.MyFunction._

// imports all the members of the object MyFunction but renames memA to // memB. Like an alias.
import com.test.MyFunction.{ memA => memB, _ }

// imports all the members except memA .
// To exclude a member rename it to _

import com.test.MyFunction.{ memA => _ , _ }

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.

class GetterSetter{
private var pvt= 0
def number = pvt

def number_=(n:Int) = {
require(n>0)

pvt = n
}
}
val gs = new GetterSetter

gs.number = 5

println(gs.number)

4.Functions

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.

def fun() = 5// We’ve defined a function that returns an Int
val testA= fun
// fun is invoked, thus testA is 5
testA()
// as testA is an Int,this line will not compile
val testA = fun_
// now as we given _ testA is a function that returns an Int
testA()
// Returns 5

Visit My Personal Blog @ danyson.github.io

--

--