Home » Scala language

Use of underscore in Scala

Use of underscore: In programming languages, some special characters have found different uses. In this article, we will learn what are all the uses of an underscore in Scala?
Submitted by Shivang Yadav, on August 09, 2019

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:

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.

12) Hiding imports

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

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

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.