F[_] and the Furious Final: A Tagless Adventure
When Scala’s Containers Run Wild But We Still Catch All the Types!
Tagless final is a hot topic today: a discussion at the Scala Users group, an interesting blog by Nicolas Rinaudo, a nice tutorial written by Ricardo Cardin at Baeldung and Noel Welsh gave a great presentation at the Scalar among many others. However, when teaching a graduate level programming language class this Summer I realized that this concept is difficult to comprehend for many students because they saw it as an overcomplicated redundancy for what they needed. I want to take a different angle at explaining it in this article.
In Scala, writing a type parameter as F[_]
means “We’re abstracting over a type constructor that itself takes one type argument.” In other words, instead of fixing your code to work with, say, Option[Int]
or List[Int]
, you can say “I’ll work with any F[Int]
as long as F
is some kind of container or context.” Values can be placed in some container and we do not care what type of this container the user decides to choose, our code can handle it.