Skip to content

Instantly share code, notes, and snippets.

@milessabin
Last active December 19, 2015 20:49
Show Gist options
  • Save milessabin/6015989 to your computer and use it in GitHub Desktop.
Save milessabin/6015989 to your computer and use it in GitHub Desktop.
Selecting type class instances by singleton types of values.
scala> import shapeless._
import shapeless._
scala> import SingletonTypes._
import SingletonTypes._
scala> :paste
// Entering paste mode (ctrl-D to finish)
trait Show[T] {
def show: String
}
object Show {
implicit def showTrue[T](implicit t: T = refine(true)) = new Show[T] { def show = "true" }
implicit def showFalse[T](implicit t: T = refine(false)) = new Show[T] { def show = "false" }
implicit def showOne[T](implicit t: T = refine(1)) = new Show[T] { def show = "One" }
implicit def showTwo[T](implicit t: T = refine(2)) = new Show[T] { def show = "Two" }
implicit def showThree[T](implicit t: T = refine(3)) = new Show[T] { def show = "Three" }
}
// Exiting paste mode, now interpreting.
defined trait Show
defined module Show
scala> def show(t: Witness)(implicit s: Show[t.T]) = s.show
show: (t: shapeless.Witness)(implicit s: Show[t.T])String
scala> show(true)
res0: String = true
scala> show(false)
res1: String = false
scala> show(1)
res2: String = One
scala> show(2)
res3: String = Two
scala> show(3)
res4: String = Three
scala> show(4)
<console>:16: error: could not find implicit value for parameter s: Show[Int(4)]
show(4)
^
scala>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment