Guest User

Untitled

a guest
Feb 24th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. /*
  2. * implicit conversion ("view"): implicit def f(x: A): B
  3. * non-view implicit: implicit def f(implicit x: A): B
  4. *
  5. * we can summon implicit conversions with `implicitly[A => B]`
  6. * we can't do that with non-view implicits
  7. * this macro provides the trait `Conditional[A, B]` that provides precisely that
  8. */
  9.  
  10. package conditional
  11.  
  12. import scala.language.experimental.macros
  13. import scala.reflect.macros.blackbox.Context
  14.  
  15. trait Conditional[A, B] {
  16. def apply(a: A): B
  17. }
  18.  
  19. object Conditional {
  20.  
  21. def impl[A : c.WeakTypeTag, B : c.WeakTypeTag](c: Context) = {
  22. import c.universe._
  23.  
  24. val a = weakTypeOf[A]
  25. val b = weakTypeOf[B]
  26.  
  27. val tree = q"""
  28. new _root_.conditional.Conditional[$a, $b] {
  29. def apply(a: $a): $b = {
  30. implicit val _a: $a = a
  31. _root_.scala.Predef.implicitly[$b]
  32. }
  33. }
  34. """
  35.  
  36. c.Expr[Conditional[A, B]](tree)
  37. }
  38.  
  39. implicit def summon[A, B]: Conditional[A, B] = macro impl[A, B]
  40.  
  41. }
Add Comment
Please, Sign In to add comment