code

Its all just ones and zeroes isn't it? 
Filed under

c#

 

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.

Filed under  //   c#   scala  

Comments [0]

Creating C#'s "Using" statement in Scala

C# first introduced me to the world of functional programming, which has led me to Scala.  One feature of C# that I used a lot is the using statement, which lets you write something like this:



using( var connection = new Connection(...)  ) {
  connection.DoStuff();
}


instead of:



Connection connection = null;

try {
   connection = new Connection( ... )
   
   connection.DoStuff();
}
finally {
  connection.Dispose();
}


The first snippet of code is smaller and more concise.  The using statement means you don't have to write boiler plate try-finally code to close your resources in the event of an exception.

Having just started developing in Scala, I was looking for something similar, here is an implementation of Using in Scala:

(Inspired by Beginning Scala by David Pollak creator of the Scala web framework Lift)



object Using {
  /*
   * Recreate C#'s Using statement
   * 
   * Use a method called apply, which in Scala can be invoked directly off the object, e.g.
   * Using(foo) instead of Using.apply(foo)
   */
  def apply[A <: {def close(): Unit}, B](param: A)(f: A => B) : B =
    try {
      f(param)
    } finally {
      param.close()
    }
}

Which can be used like this:



using( new Connection(...)  ) { connection =>
   connection.DoStuff();
 }


So there are a few things going on here:

  • "object Using" is the syntax for a singleton class named Using
  • By naming our method "apply" we can take advantage of some Scala syntactic sugar to enable us to invoke it like "Using( ... )" instead of the traditional "Using.apply( ... )"
  • The method apply takes two parameter lists, the first (param: A) has one parameter, the item to be closed, and the second (f: A => B) which takes a function which will be invoked in a try-finally clause in case it throws an exception

Filed under  //   c#   scala  

Comments [0]