Common Uses of the Underscore in Scala

Importing All Members from a Package

The underscore can import every member of a package or object.

import scala.io._

Default Value Initialization for Variables

Assigns the default value for a type to a var field.

class Container {
  var itemLabel: String = _
  var itemCount: Int = _
}

Tuple Element Access

Access elements of a tuple using their index, starting from 1.

val coordinates = (10.5, 20.3, 30.1)
val xCoord = coordinates._1
val yCoord = coordinates._2
val zCoord = coordinates._3

Simplifying Anonymous Functions

The underscore acts as a placeholder for parameters in anonymous functions.

Single Parameter Functon

object FunctionSimplification {
  def main(args: Array[String]): Unit = {
    val data = Vector(5, 10, 15)
    
    // Explicit parameter and type
    val result1 = data.map((n: Int) => n * 2)
    
    // Omit type
    val result2 = data.map((n) => n * 2)
    
    // Omit parentheses for single parameter
    val result3 = data.map(n => n * 2)
    
    // Use underscore as placeholder
    val result4 = data.map(_ * 2)
  }
}

Multiple Parameter Function

object MultiParamFunction {
  def main(args: Array[String]): Unit = {
    val numbers = Vector(2, 3, 4)
    
    // Full anonymous function
    val product1 = numbers.foldLeft(1)((x: Int, y: Int) => x * y)
    
    // Omit types
    val product2 = numbers.foldLeft(1)((x, y) => x * y)
    
    // Use underscores as placeholders
    val product3 = numbers.foldLeft(1)(_ * _)
  }
}

Wildcard in Pattern Macthing

Acts as a catch-all case, similar to a default branch.

object PatternWildcard {
  def main(args: Array[String]): Unit = {
    val num1 = 100
    val num2 = 20
    val opChar: Char = '%'
    
    val outcome = opChar match {
      case '+' => num1 + num2
      case '-' => num1 - num2
      case '*' => num1 * num2
      case '/' => num1 / num2
      case _   => "Unsupported operation"
    }
  }
}

Tags: Scala programming Syntax Functional Programming

Posted on Tue, 12 May 2026 18:11:42 +0000 by burge124