Created
August 27, 2014 12:23
-
-
Save ClaireNeveu/81f2a9782de131fdfe15 to your computer and use it in GitHub Desktop.
Type Class Resolution Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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