Splitting Hair With Scala Trait

When comes to trait there are Object Oriented (OO) and Functional Programming (FP) ways to look at it. From the OO perspective, trait is treated similar to Java interface where it is implemented with a class. On the other hand, in FP perspective , trait is a type class. Some books did not go further after showing how trait is used in an OO setup. It raises questions when it is used as type class in other examples.

For example, in OO way,

trait Foo[T] {
  def plus(a: T, b: T): T
}

class Bar extends Foo[String] {
  override def plus(a: String, b: String) = a + b
}

val bar = new Bar
bar.plus("10", "aa")

For the same use case in type class approach we have,

implicit object FooString extends Foo[String] {
  override def plus(a: String, b: String) = a + b
}

def add[T: Foo](a: T, b: T)(implicit f: Foo[T]) = 
  f.plus(a, b)

add("aa", "bb")

I would prefer type class pattern approach over interface implementation because type class is more flexible.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s