Scala Extension methods via implicit classes

Kfir Bloch | February 26th 2013 | Scala

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


case class Cat(name : String, kittens : Seq[Cat] = Nil)

object implicits{

implicit class SmellyCat(cat : Cat) {
 def hasKittens : Boolean = cat.kittens.size > 0
 }

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:

class ExtensionFunction extends WordSpec with ShouldMatchers with MustMatchers{

"extension function " should {
 "extend function of cat " in {

import implicits._
 val cat1 = Cat("Philip")
 cat1.hasKittens should equal(false)

val cat2 = Cat("Kozmo", Seq(Cat("Mitzi")))
 cat2.hasKittens should equal(true)

   }
  }
}

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


By Kfir Bloch
Wix

Leave a Reply

1 comment

We are always looking for excellent people. Browse Jobs Here   

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

Have any questions? Email academy@wix.com.

Find out what’s coming up at Wix Engineering:

Subscribe to our newsletter for updates, events and more.