×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Uses of Underscore (_) in Scala

By IncludeHelp Last updated : October 10, 2024

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

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

Existential Types

These types are the ways of abstracting over data types,

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

Higher kind type parameters

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

class incl [u[ _ ]]

Ignored variables

The ignored variables are declared using _. For example,

val _ = 67

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[_] => }

Wildcard patterns

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

case (_) : //code

Wildcard imports

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

import java.util._

Joining operators to letter

Sample,

def fn_! (x : float) = 5

Assignment operator

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

def include_ = { ... }

Placeholder syntax

A placeholder is an anonymous function. Sample,

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

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 _ 

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.

Hide imports of methods

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

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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.