Scala Extension methods via implicit classes

Updated: Jun 18, 2018

In this post i will demonstrate a nice trick to add “extension methods” for a given class.

Note: The feature is based on implicit class feature and available only in Scala 2.10

A class Cat has a name and a list of kittens. in this example we add a method named “hasKittens()” to the Cat class. This is done by creating the implicit class SmellyCat which implicitly wraps our Cat instance when calling “hasKittens()”.

The following test shows the usage of this feature:

To use the extended function you need to import the class (import implicits._).

Note: implicit class cannot be on the top level of the project and must be wrapped inside an object.

#Extension #scala #Extensionmethods #implicitclass

4,842 views0 comments
  • Black Twitter Icon
  • Black YouTube Icon

At Wix Engineering we develop some of the most innovative cloud-based web applications that influence our +180 million users worldwide.

Have any questions?

Trademarks and logos of other parties appearing in this post are the property of their respective holders.

Get Wix Engineering Straight to Your e-mail