Syntactic Sugar for Type Classes

Type classes is IMHO one of the most important features of Scala. However, using them can be awkward:

 

trait TypeClass[T] {
  def foo(t: T): Int
}

def foo[T: TypeClass](t: T) = implicitly[TypeClass[T]].foo(t)

 

Here's a way to make it a bit nicer to use.

 

trait TypeClassExt[T] {
  def foo: Int
}

trait TypeClass[T] extends (T => TypeClassExt[T]) {
  def foo(t: T): Int
  def apply(t: T) = 
    new TypeClassExt[T]{
      def foo = TypeClass.this.foo(t)
    }
  }

def foo[T: TypeClass](t: T) = t.foo

 

HTH

Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com