Conversions
1. Function Reassignment
Using the underscore allows transforming a method into a function.
Example:
object Main {
def main(args: Array[String]) {
// Code
}
}
2. Variable Argument Sequence
Converting a sequence into variable arguments is possible with seqName: ‘_’.
Below is the Scala program to implement the approach:
def sum(args: Int*): Int = {
args.reduce(_ + _)
}
val sumable = Seq(4, 5, 10, 3)
val sumOfSumable = sum(sumable: _*) // Converting sumable to varargs
assert(sumOfSumable == 22)
Output:
3. Partially-Applied Function
Creating a partially applied function involves providing only some arguments. Unprovided parameters are substituted with underscores.
Below is the Scala program to implement the approach:
def sum(x: Int, y: Int): Int = x + y
val sumToTen = sum(10, _: Int)
val sumFiveAndTen = sumToTen(5)
assert(sumFiveAndTen == 15)
Output:
Additionally, underscores can be used to ignore parameter groups in functions with multiple parameter groups:
Example:
def bar(x: Int, y: Int)(z: String, a: String)(b: Float, c: Float): Int = x
val foo = bar(1, 2) _ // Ignoring the third parameter group
assert(foo(“Some string”, “Another string”)(3/5, 6/5) == 1)
4. Assignment Operators (Setters overriding)
Overriding default setters is another form of conversion using underscores.
Below is the Scala program to implement the approach:
class Product {
private var a = 0
def price: Int = a
def price_=(i: Int): Unit = {
require(i > 10, "Price must be greater than 10")
a = i
}
}
val product = new Product
product.price = 20
assert(product.price == 20)
try {
product.price = 7 // This will fail because 7 is not greater than 10
assert(false, "Price must be greater than 10")
} catch {
case _: IllegalArgumentException => assert(product.price != 7)
}
Output:
What are All the Uses of an Underscore in Scala?
The underscore (_) is a symbol frequently employed in Scala, serving as a handy tool to simplify and condense code. While it’s dubbed “syntactic sugar” for its ability to streamline code, its extensive use can sometimes lead to confusion and make the learning process more challenging.
This article focuses on discussing the various common uses of underscores in Scala, shedding light on their diverse functionalities.
Table of Content
- Pattern Matching and Wildcards
- Ignored Parameter
- Conversions
- Miscellaneous Usages
- Conclusion
- FAQs
Contact Us