Ignored Parameter
You can think of the underscore as a handy tool in coding that lets you disregard variables and types that aren’t needed anywhere in your code. It’s like saying, “Hey, I know this exists, but I’m not going to use it here, so let’s just move on without worrying about it.
1. Ignored Parameter
Example:
val ints = (1 to 4).map(_ => “Int”)
assertEquals(ints, Vector(“Int”, “Int”, “Int”, “Int”))
Using the underscore, we ignored whatever value we have in the map anonymous function; we just return Int for each element of the range. We may use the anonymized parameter as a placeholder in function. This makes the code clean though less explicit.
Example:
val prices = Seq(10.00, 23.38, 49.82)
val pricesToInts = prices.map(_.toInt)
assertEquals(pricesToInts, Seq(10, 23, 49))
Here, the mapping is equivalent to:
prices.map(x => x.toInt)
We can also use the underscore to access nested collections.
Below is the Scala program to implement the approach:
val items = Seq(("candy", 2, true), ("cola", 7, false), ("apple", 3, false), ("milk", 4, true))
val itemsToBuy = items
.filter(_._3) // filter in only available items (true)
.filter(_._2 > 3) // filter in only items with price greater than 3
.map(_._1) // return only the first element of the tuple; the item name
// Print the output to verify
println(itemsToBuy)
Output:
We already saw a hidden import in pattern matching, that can also be referenced as ignoring things. We can ignore a given module and import the rest.
Example:
import org.junit.{Before => _, _}
With this, we’ve imported all members of the junit package except (ignoring) Before.
2. Ignored Variable
When we don’t care about variables for constructed entries, we can ignore them using the underscore.
For example, we want only the first element in a split string:
val text = “a,b”
val Array(a, _) = text.split(“,”)
assertEquals(a, “a”)
The same is applicable if we want only the second one:
val Array(_, b) = text.split(“,”)
assertEquals(b, “b”)
We can extend this to more than two entries:
val text = “a,b,c,d,e”
val Array(a, _*) = text.split(“,”)
assertEquals(a, “a”)
To ignore the rest of the entries after the first, we use the underscore together with.
We can also ignore randomly using the underscore for any one entry we don’t want:
val Array(a, b, _, d, e) = text.split(“,”)
assertEquals(a, “a”)
assertEquals(b, “b”)
assertEquals(d, “d”)
assertEquals(e, “e”)
3. Variable Initialization to Its Default Value
When the initial value of a variable is not necessary, we can use the underscore as default:
var x: String = _
x = “real value”
println(x)
This doesn’t work for local variables; local variables must be initialized.
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