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’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.
This is a page from my book, Functional Programming, Simplified
The main goals for this lesson are:
Intellij IDEA has a reall nice help-tip hover tool that helps to explain some of Scala’s advanced language features. In this case the code
Monad[M[_]] is a higher-kinded type, which I hope to explain more in my new book.
Scala FAQ: Can you share an example of how to create an implicit class in Scala 2.10?
Sure. As the question implies, the implicit class functionality changed in Scala 2.10, so let's take a look at the new syntax.
Rather than create a separate library of
String utility methods, like a
StringUtilities class, you want to add your own behavior(s) to the
String class, so you can write code like this:
UPDATE: This example shows how to create an implicit method in Scala 2.9 or older. You can use a slightly simpler approach with Scala 2.10 and newer, which I've documented in this Scala 2.10 implicit class example.
I'm not going to do much writing here today, but instead I'll just demonstrate how an implicit method argument works with implicit fields in Scala. Without any further ado, here's some code:
When you're working in the Scala REPL and want to see what methods are available on a class/object, you can create an instance of an object, follow that with the "." character, and then press the [Tab] key. This process, known as "tab completion" in the REPL, gives you a preliminary list of methods that can be called on the object.
Here's what this looks like when we try it on an Int object: