implicit

Implicit methods/functions in Scala 2 and 3 (Dotty extension methods)

Table of Contents1 - Scala 2: Create the method in an implicit class2 - Scala 3 (Dotty): Adding methods to closed classes with extension methods

Scala lets you add new methods to existing classes that you don’t have the source code for, i.e., classes like String, Int, etc. For instance, you can add a method named hello to the String class so you can write code like this:

"joe".hello

which yields output like this:

"Hello, Joe"

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).

A Scala 2.10 (and newer) implicit class example (how to add new functionality to closed classes)

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.

Background

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:

A Scala implicit method argument and field example

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:

Scala REPL: How to show more methods on a class/object in the REPL

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: