Scala – Placeholder Syntax

  • date 24th May, 2021 |
  • by Prwatech |

How to use placeholder syntax in scala


The requirement for making everything brief lead Scala to raise something many refer to as the Placeholder sentence structure. Scala permits the utilization of underscore (meant as ‘_’) to be utilized as placeholders for at least one boundaries. we can consider the underscore to something that should be filled in with a worth.

In Scala, the placeholder syntax is a concise way to define anonymous functions, especially useful when passing functions as arguments to higher-order functions like map, filter, or reduce. Placeholder syntax allows developers to write compact and readable code by omitting explicit function parameters and using underscores (_) to represent placeholders for parameters.

For example, when using map on a collection, instead of explicitly defining a named function with a single parameter, you can use placeholder syntax like * 2) to double each element of the collection. Here, _ represents the parameter passed to the anonymous function.

Placeholder syntax is particularly handy for simple, one-line transformations where the function logic is concise and easily understood. It promotes functional programming principles by emphasizing the behavior of functions rather than their specific parameter names.

When using placeholder syntax, it’s important to note that each underscore (_) represents a different parameter position in the function. For multiple parameters, you can use consecutive underscores (_ + _) to represent each parameter sequentially.

Use case 1:

scala> val somenumbers= List(1,2,3,4,5)
scala>  somenumbers.foreach(println _)

2Use case 2:

Suppose we want to check if the number is greater than 5.
scala> val somenumbers= List(3,4,5,8,10,9)
scala> somenumbers.filter(_ > 5)

Use case 3:

Suppose we want to add two numbers.
scala> val f = (_: Int) + (_: Int)
scala> f(15, 10)

Quick Support

image image