Created
February 13, 2013 00:47
-
-
Save johnynek/4780255 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.twitter.bijection | |
/** Deals with the type-system issue around resolving implicit bijections. | |
* Bijection[A,B] or Bijection[B,A], which should | |
* be equivalent. Only use this type as an implicit parameter. | |
*/ | |
import scala.annotation.implicitNotFound | |
@implicitNotFound(msg = "Cannot find ImplicitBijection type class from ${A} to ${B}") | |
sealed trait ImplicitBijection[A, B] extends (A => B) with java.io.Serializable { | |
def bijection: Bijection[A, B] | |
def apply(a: A) = bijection.apply(a) | |
def invert(b: B) = bijection.invert(b) | |
} | |
case class Forward[A, B](override val bijection: Bijection[A,B]) extends ImplicitBijection[A, B] | |
case class Reverse[A, B](inv: Bijection[B, A]) extends ImplicitBijection[A, B] { | |
lazy val bijection = inv.inverse | |
} | |
trait LowPriorityImplicitBijection extends java.io.Serializable { | |
implicit def reverse[A, B](implicit bij: Bijection[B, A]): ImplicitBijection[A, B] = Reverse(bij) | |
} | |
object ImplicitBijection extends LowPriorityImplicitBijection { | |
implicit def forward[A, B](implicit bij: Bijection[A, B]): ImplicitBijection[A, B] = Forward(bij) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment