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.

1. Module Import

  • When we import packages in our code, we sometimes use an underscore to indicate that we want to import all or some members of the module.
  • Importing all members from the package org.junit is done with an underscore, similar to a wildcard import in Java.
  • If we want to import all members except one, say Before, we specify {Before => _}.
  • Renaming a member while importing is also possible. For instance, importing all members but renaming Before to B4 is done with {Before => B4, _}.

Syntax:

import org.junit._
import org.junit.{Before => _, _}
import org.junit.{Before => B4, _}

2. Existential Types

  • The underscore is used as a wildcard to match all types in type creators like List, Array, Seq, Option, or Vector. This allows flexibility in handling various types of data.
  • For instance, in a function to calculate the length of a list of lists (List[List[_]]), we can use _ to accept any type of element in the inner lists.

Below is the Scala program to implement the approach:

Scala
def itemTransaction(price: Double): String = {
  price match {
    case 130.0 => "Buy"
    case 150.0 => "Sell"
    case _ => "Need approval"
  }
}
println(itemTransaction(130)) 
println(itemTransaction(150))
println(itemTransaction(70))
println(itemTransaction(400)) 

Output:


Existential Types

3. Matching

  1. In Scala, the match keyword is used for pattern matching. The underscore symbol serves to catch all possible cases not handled by explicitly defined cases.
  2. Consider a scenario where we decide whether to buy or sell an item based on its price. If the price is $130, we buy; if it’s $150, we sell. For any other price, we need approval.

Below is the Scala program to implement the approach:

Scala
def itemTransaction(price: Double): String = {
  price match {
    case 130 => "Buy"
    case 150 => "Sell"
    case _ => "Need approval"
  }
}
itemTransaction(130) 
itemTransaction(150) 
itemTransaction(70) 
itemTransaction(400) 

Output:

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