Scala lets you add new methods to existing classes that you don’t have the source code for, i.e., classes like
Int, etc. For instance, you can add a method named
hello to the
String class so you can write code like this:
which yields output like this:
Admittedly that’s not the most exciting method in the world, but it demonstrates the end result: You can add methods to a closed class like
String. Properly (tastefully) used, you can create some really nice APIs.
In this article I’ll show how you can create implicit methods (also known as extension methods) in Scala 2 and Scala 3 (Dotty).
If you happen to be using Dotty (Scala 3) and find that the
f string interpolator isn’t working, it’s a known bug. (It was implemented with a macro, and the old, experimental macro system has been dropped.) I’m writing this in January, 2019; I don’t know when it will work again. You can use the Java/Scala String.format method until it’s fixed:
val pi = scala.math.Pi println( "%1.5f".format(pi) )
As a brief note to self, here’s an early example of the syntax of Intersection Types in Scala 3 (Dotty):
If you’re interested in the future of Scala, i.e., Scala 3, also known as Dotty, Martin Odersky recently shared a working draft document titled, Functional Typelevel Programming in Scala. See the “Files Changed” link on that page for the complete working document.
If you’re interested in the future of Scala, specifically Scala 3, the official Scala blog has an interesting article titled, Macros: The Plan for Scala 3. A beneficial part of reading at least part of the article is that you can learn a little bit about Tasty, “the high-level interchange format for Scala 3.”
- become more opinionated
- eliminate inconsistencies and puzzlers
- build on strong foundations
- consolidate language constructs to improve: consistency, safety, ergonomics, performance
As Ms. Robinson writes, “Scala was a language toolbox, and that leads to fragmentation. Scala 3 wants to become more opinionated.”