Conversions

1. Function Reassignment

Using the underscore allows transforming a method into a function.

Example:

object Main {

def main(args: Array[String]) {

// Code

}

}

2. Variable Argument Sequence

Converting a sequence into variable arguments is possible with seqName: ‘_’.

Below is the Scala program to implement the approach:

Scala
def sum(args: Int*): Int = {
  args.reduce(_ + _)
}
val sumable = Seq(4, 5, 10, 3)
val sumOfSumable = sum(sumable: _*) // Converting sumable to varargs
assert(sumOfSumable == 22)

Output:

Variable Argument Sequence

3. Partially-Applied Function

Creating a partially applied function involves providing only some arguments. Unprovided parameters are substituted with underscores.

Below is the Scala program to implement the approach:

Scala
def sum(x: Int, y: Int): Int = x + y
val sumToTen = sum(10, _: Int)
val sumFiveAndTen = sumToTen(5)
assert(sumFiveAndTen == 15)

Output:

Partially-Applied Function

Additionally, underscores can be used to ignore parameter groups in functions with multiple parameter groups:

Example:

def bar(x: Int, y: Int)(z: String, a: String)(b: Float, c: Float): Int = x

val foo = bar(1, 2) _ // Ignoring the third parameter group

assert(foo(“Some string”, “Another string”)(3/5, 6/5) == 1)

4. Assignment Operators (Setters overriding)

Overriding default setters is another form of conversion using underscores.

Below is the Scala program to implement the approach:

Scala
class Product {
  private var a = 0
  def price: Int = a
  def price_=(i: Int): Unit = {
    require(i > 10, "Price must be greater than 10")
    a = i
  }
}

val product = new Product
product.price = 20
assert(product.price == 20)

try {
  product.price = 7 // This will fail because 7 is not greater than 10
  assert(false, "Price must be greater than 10")
} catch {
  case _: IllegalArgumentException => assert(product.price != 7)
}

Output:

Assignment Operators (Setters overriding)

What are All the Uses of an Underscore in Scala?

The underscore (_) is a symbol frequently employed in Scala, serving as a handy tool to simplify and condense code. While it’s dubbed “syntactic sugar” for its ability to streamline code, its extensive use can sometimes lead to confusion and make the learning process more challenging.

This article focuses on discussing the various common uses of underscores in Scala, shedding light on their diverse functionalities.

Table of Content

  • Pattern Matching and Wildcards
  • Ignored Parameter
  • Conversions
  • Miscellaneous Usages
  • Conclusion
  • FAQs

Similar Reads

Pattern Matching and Wildcards

The underscore serves as a wildcard and is commonly used in Scala for matching unknown patterns. It’s often one of the earliest applications of the underscore we encounter when we start learning Scala. Now, let’s explore a few examples to understand its usage better....

Ignored Parameter

You can think of the underscore as a handy tool in coding that lets you disregard variables and types that aren’t needed anywhere in your code. It’s like saying, “Hey, I know this exists, but I’m not going to use it here, so let’s just move on without worrying about it....

Conversions

1. Function Reassignment...

Miscellaneous Usages

1. Connecting Letters to Operators or Punctuation...

Conclusion

Underscores in Scala exemplify the elegance of simplicity, offering a myriad of functionalities that streamline coding, enhance readability, and unlock new possibilities for developers. Embracing the diverse uses of underscores empowers Scala programmers to write cleaner, more expressive, and more robust code....

FAQs

What does the underscore signify in Scala?...

Contact Us