Implicit Classes Scala 2.10 Extension Methods

0 comments

Having worked with C# in the last couple of months, writing extension methods was one of the cool features that I appreciated a lot! Extension methods are just a way to add new mwthods to the existing set of types. For example, the double type has several methods as part of the Scala API. If you now want to add a method that finds the reciprocal of a double, the first thing that comes naturally would be to write a helper utility function that does this for us. With extension methods, you can make that helper utility function look like as though it is part of the API itself. So let's see how to write the reciprocal extension method on a double!

  implicit class DoubleExtensions(val d: double) extends AnyVal {
    def reciprocal = 1 / d
  }
A few points to note on the code snippet
  • The implicit keyword makes the primary constructor of the class available for implicit conversions
  • The implicit classes may be defined inside a trait, class or an object - good practice
  • Only one non implicit argument is allowed in the primary constructor (the val d: double in the case above)
  • There may not be any method, member or object in scope with the same name as the implicit class
I find this pretty neat and very simple rules surrounding implicit classes!

Pattern Matching Scala Collections

0 comments

One of the astonishing features that Scala has is the pattern matching mechanism. Think of it like a Java Switch statement on Steroids. Pattern matching is such a powerful concept in Scala. Once you start using them, you'll find it inevitable to not using them. Let's look at some examples

You want to pattern match a List based on the number of elements in the List :

def patternMatch = {
  val matchResult = List(1,2,3,4,5) match {
    case Nil => "Matches an empty List"
    case head :: Nil => "Matches a List that has exactly one element"
    case head :: tail => "Matches a List that hast at-least one element"
  }
}

What is happening in the above code snippet is that, the myList is run through the case blocks and it is obvious that myList has more then one element init and hence the last case statement is matched and the following statement is returned as the matchResult.

If you are wondering what the case syntax is all about, here is a quick description of what it is:

case pattern => expression

The case is a Scala keyword, the pattern is what you specify for the supplied value to be checked against and the expression is what you want to be returned if the pattern matches. Simple or?