Uses of Underscore (_) in Scala

In this tutorial, we will learn about the various uses of underscore (_) with examples in Scala. Submitted by Shivang Yadav, on August 09, 2019

What is a Underscore (_)?

Underscore (_) character is reserved in Scala and has multiple usages in the programming language.

Various Uses of Underscore (_)

Based on functions that use the underscore have the following usages:

1) Existential Types

These types are the ways of abstracting over data types,

def functn(l: List[Option[_]]) = {

2) Higher kind type parameters

A higher kind type is a constructor that contains a type constructor itself. Sample,

class incl [u[ _ ]]

3) Ignored variables

The ignored variables are declared using _. For example,

val _ = 67

4) Ignored names of self-types

Merging two traits without extending each other is self type. Instead of names of self types, programmers can use the ignored names. Sample,

trait incl { _: seq[_] => }

5) Wildcard patterns

In pattern matching, a wildcard pattern is used to match the unmatched case. Sample,

case (_) : //code

6) Wildcard imports

To import all classes of a package, the wildcard import is used. Sample,

import java.util._

7) Joining operators to letter


def fn_! (x : float) = 5

8) Assignment operator

An assignment operator is an operator that assigns a value to the given variable/method. For example,

def include_ = { ... }

9) Placeholder syntax

A placeholder is an anonymous function. Sample,

list (a, b, c) map(_+c)

10) Method values

If a method returns a single value and program directly uses it, then _ can be used instead of its name. For example, iterating over a list,

list (a, b, c) foreach println _ 

11) Default initializers

The initialization of variables without using values is done using underscore _. For example,

var a : Int = _ // value is 0 i.e. default value.

You can hide imports of scala methods is done using the wildcard _.

import java.util.{ArrayList => _, _}

Comments and Discussions!

Copyright © 2023 All rights reserved.