Miscellaneous Usages
1. Connecting Letters to Operators or Punctuation
Sometimes, we want to make our variable names clearer by incorporating punctuation. However, unlike alphanumeric characters, we can’t directly use punctuation in variable names. So, we cleverly join letters to punctuation using underscores.
Example:
Scala def list_++(list: List[_]): List[_] = List.concat(list, list)
val concatenatedList = list_++(List(2, 5))
assertEquals(concatenatedList, List(2, 5, 2, 5))
In this snippet, list_++ is a function that concatenates a given list with itself, mimicking the behavior of the ++ operator.
2. Numeric Literal Separator (Scala 2.13+)
Scala 2.13 introduced a handy feature: the ability to use underscores as separators in numeric literals, making them more readable.
Below is the Scala program to implement the approach:
var x = 1_000_000
println(x)
var pi = 3.14e-02
println(pi)
pi = 3.14e-02
Output:
Underscores make it easier to parse large numeric literals at a glance.
3. Higher-Kinded Types
Higher-kinded types are types that abstract over other types, allowing for powerful abstractions. In Scala, we can use underscores to define them succinctly.
Below is the Scala program to implement the approach:
trait ObjectContainer[T[_]] { // higher-kinded type parameter
def checkIfEmpty[A](collection: T[A]): Boolean
}
object SeqContainer extends ObjectContainer[Seq] {
override def checkIfEmpty[A](collection: Seq[A]): Boolean = collection.isEmpty
}
var seqIsEmpty = SeqContainer.checkIfEmpty(Seq(7, "7"))
assert(seqIsEmpty == false)
seqIsEmpty = SeqContainer.checkIfEmpty(Seq())
assert(seqIsEmpty == true)
Output:
In this example, ObjectContainer defines a trait with a higher-kinded type parameter T[_], allowing it to operate on various collection types. We then implement it for Seq, demonstrating its usage.
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