The Underscore Placeholder in Scala

Mohammad Irfan Mar 11, 2022
  1. Use Underscore to Import Statement in Scala
  2. Use Underscore in a for Loop in Scala
  3. Use Underscore in the Case Pattern in Scala
  4. Use Underscore in a Variable in Scala
  5. Use Underscore Numeric Values in Scala
The Underscore Placeholder in Scala

This tutorial will discuss the underscore (_) and its uses in Scala. In Scala, underscore (_) is a placeholder that represents the absence of a value or variable.

We can use it to assign a default value to a variable and import all the classes of a package in the code.

Use Underscore to Import Statement in Scala

Using underscore it to import packages is the common use of the placeholder in Scala. For example, if we want to import all the break functions, use the underscore.

Scala
 scalaCopyimport scala.util.control.Breaks._
object MyClass {
   def main(args: Array[String]) {
     breakable {
            for(i<-1 to 10 by 2){
                if(i==5)
                    break
                else
                    println(i)
            }
        }
   }
}

Output:

 textCopy1
3

Use Underscore in a for Loop in Scala

We use the underscore within the foreach to traverse the list elements. We used it in place of any reference variable of the list.

Scala
 scalaCopyobject MyClass {
    def main(args: Array[String]) {
     List(1,2,3,4).foreach(println(_))
    }
}

Output:

 textCopy1
2
3
4

Use Underscore in the Case Pattern in Scala

We can also use it to set a default case in the case patterns. In other languages, we use the default keyword to define a default case that executes when no match case is found, and in Scala works similarly.

Scala
 scalaCopyobject MyClass {
   def matchTest(x: Int): String = x match {
     case 1 => "one"
     case 2 => "two"
     case _ => "anything other than one and two"
   }
   def main(args: Array[String]) {
     val r = matchTest(2)
     val r2 = matchTest(20)
     println(r)
     print(r2)
   }
}

Output:

 textCopytwo
anything other than one and two

Use Underscore in a Variable in Scala

We can use the underscore to refer to the default value in a variable declaration. As in the example below, we declare an integer variable whose default value is 0.

Scala
 scalaCopyobject MyClass {
  var i: Int = _
   def main(args: Array[String]) {
     print(i)
   }
}

Output:

 textCopy0

Use Underscore Numeric Values in Scala

This is another case of using the underscore. We are using it to make numeric values more readable.

When we have a large value, it isn’t easy to read it once. It is also known as a numeric separator.

Scala
 scalaCopyobject MyClass {
   def main(args: Array[String]) {
     var i: Int = 1_000_000
     print(i)
   }
}

Output:

 textCopy1000000