code

Its all just ones and zeroes isn't it? 
« Back to blog

Implicits in Scala (similar to extension methods in C#)

In my past I've done a lot of development with C#, and loved the new language features introduced in 3.5 such as LINQ, extension methods, lambdas etc.

Here's how you can implement extension methods (in C# terminology) in Scala using Implicits.  The goal in this example is to recreate toDictionary that exists in C#, and allow us to take a list of things and put them into a Dictionary (or HashMap in Scala) in one line.


package org.acme

import scala.collection.mutable.HashMap

class IterableExtensions[A,B](pairs : Iterable[(A,B)] ) {
   def toHashMap() : HashMap[A,B] = {
      val hashMap = new HashMap[A,B]
      hashMap ++= pairs
      hashMap
   }
}

object IterableExtensions {
    implicit def IterableExtensions[A,B](i : Iterable[(A,B)]) = new IterableExtensions(i)
}

(Check out this good introduction to implicits in Scala).   Basically we're defining a method toHashMap, and putting it in the singleton IterableExtensions which we can later import, and use like this:


package org.acme

import scala.collection.mutable.HashMap
import org.acme.IterableExtensions._


class Person( _name : String, _age : Int ) {
   def getName = _name
   def getAge = _age
}


class Test {
   // Compose a list of pairs in the form (name, age)
   val peopleWithAge = List ( new Person("John",25), new Person("Bob", 30), new Person("Frank", 35))

   // Put those pairs into a HashMap
   val peopleByAge = peopleWithAge.map( p => p.getAge ).toHashMap
}

In the above code we've imported the IterableExtensions, and they are now accessible off the Iterable interface, which is most (or all?) collections and lists.

Comments (0)

Leave a comment...

 
To leave a comment on this posterous, please login by clicking one of the following.
Posterous-login     twitter