Last active
December 14, 2015 08:08
-
-
Save lyricallogical/5055235 to your computer and use it in GitHub Desktop.
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.qtamaki.typeclass | |
trait Hoge[A] { | |
def age(a: A): A | |
def sage(a: A): A | |
def hoge(a: A): A | |
} | |
object Hoge { | |
implicit def IntHoge: Hoge[Int] = | |
new Hoge[Int] { | |
def age(a: Int) = a + 1 | |
def sage(a: Int) = a - 1 | |
def hoge(a: Int) = a * a | |
} | |
implicit def BoolHoge: Hoge[Boolean] = | |
new Hoge[Boolean] { | |
def age(a: Boolean) = true | |
def sage(a: Boolean) = false | |
def hoge(a: Boolean) = ! a | |
} | |
def runAge[A](a:A)(implicit ev: Hoge[A]): A = { | |
ev.age(a) | |
} | |
def runSage[A](a:A)(implicit ev: Hoge[A]): A = { | |
ev.sage(a) | |
} | |
def runHoge[A](a:A)(implicit ev: Hoge[A]): A = { | |
ev.hoge(a) | |
} | |
} |
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.qtamaki.typeclass | |
import Hoge._ | |
object Main { | |
def main(args: Array[String]): Unit = { | |
// defined by Library author | |
println(runAge(123)) | |
println(runSage(123)) | |
println(runHoge(123)) | |
println(runAge(true)) | |
println(runSage(true)) | |
println(runHoge(true)) | |
// defined by Main author | |
println(runAgeMain(123)) | |
println(runSageMain(123)) | |
println(runHogeMain(123)) | |
println(runAgeMain(true)) | |
println(runSageMain(true)) | |
{ | |
val intHoge = implicitly[Hoge[Int]] | |
import intHoge._ | |
println(age(123)) | |
println(sage(123)) | |
println(hoge(123)) | |
} | |
{ | |
val intBoolean = implicitly[Hoge[Boolean]] | |
import intBoolean._ | |
println(age(true)) | |
println(sage(true)) | |
println(hoge(true)) | |
} | |
} | |
def runAgeMain[A](a:A)(implicit ev: Hoge[A]): A = { | |
ev.age(a) | |
} | |
def runSageMain[A](a:A)(implicit ev: Hoge[A]): A = { | |
ev.sage(a) | |
} | |
def runHogeMain[A](a:A)(implicit ev: Hoge[A]): A = { | |
ev.hoge(a) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment