Skip to content

Instantly share code, notes, and snippets.

@ClaireNeveu
Created August 27, 2014 12:23
Show Gist options
  • Save ClaireNeveu/81f2a9782de131fdfe15 to your computer and use it in GitHub Desktop.
Save ClaireNeveu/81f2a9782de131fdfe15 to your computer and use it in GitHub Desktop.
Type Class Resolution Example
package com.main
import com.model.Model
import com.typeclass._
object Main extends App {
import com.alternate._
val bar = Model(1, 2)
println("The result is: " + foo(bar))
}
package com.model
import com.typeclass.CanFoo
case class Model(one: Int, two: Int)
object Model {
implicit val modelFoo = new CanFoo[Model] {
def foo(m: Model) = m.one
}
}
package com
import com.model.Model
package object typeclass {
def foo[A: CanFoo](a: A): Int = implicitly[CanFoo[A]].foo(a)
}
package object alternate {
import com.typeclass.CanFoo
implicit val modelFoo = new CanFoo[Model] {
def foo(m: Model) = m.two
}
}
package com.typeclass
trait CanFoo[A] {
def foo(x: A): Int
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment