types

Duck typing

Imagine that you want to proceed any instance or object that realizes a given contract i.e. that implements a given set of specific methods. The classical approach tells you to create a new abstraction (an Interface in Java, a Trait in Scala) that provides all the required method signatures. For instance:
/**
 * Using a trait
 */

trait Omnipotent {
  def doThis: String
  def doThat: String
}

def doEverything(o: Omnipotent) = {
  println(o.doThis)
  println(o.doThat)
}

object deity extends Omnipotent {
  def doThis: String = "This is done !!"
  def doThat: String = "That is done !!"
  def doTheRest: String = "Everything's done!!"
}

doEverything(deity)
Now, if you want to do the same thing without defining any additional trait, you can use a type definition instead:
/**
 * Using a type
 */

type Omnipotent = {
  def doThis: String
  def doThat: String
}

def doEverything(o : Omnipotent) = {
  println(o.doThis)
  println(o.doThat)
}

object deity {
  def doThis: String = "This is done !!"
  def doThat: String = "That is done !!"
  def doTheRest: String = "Everything's done!!"
}

doEverything(deity)
Compared to the previous example, the most important difference here is that the deity object doesn't extend anything, but is explicitly of type Omnipotent.

Tuple patterns

In this post I'd like to present a basic but useful feature:
When you need to quickly create a method that returns a set of data instead of only one instance of an existing class, you can use tuples (and the corresponding pattern matching).
Imagine that you need to define a method that takes 2 Ints as parameters and returns 2 Ints, without creating an additional class with 2 attributes. You can return a Tuple as done in the following example:

// returns the sum and product of 2 Ints
def sumAndProduct(n:Int, m:Int) = (n+m, n*m)

Thanks to Tuple patterns, invoking this method and getting the sum and product as returned by the function is straightforward:
val (sum, product) = sumAndProduct(5,6)
println(sum) // prints "11"
println(product) // prints "30"
The tuple values can also be accessed this way:
val ret = sumAndProduct(5,6)
println(ret._1) // prints "11"
println(ret._2) // prints "30"
Can't be easier :))
Syndicate content