Created
          April 11, 2017 15:38 
        
      - 
      
- 
        Save kolemannix/8b85d68c44a685e08aa2c28213f3d560 to your computer and use it in GitHub Desktop. 
    Implicit isomorphisms with ScalaZ
  
        
  
    
      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
    
  
  
    
  | import scalaz.Isomorphism.<=> | |
| /** Our example Isomorphism */ | |
| trait StringIntIso { | |
| implicit object StringIntIso extends (String <=> Int) { | |
| override val to: (String) => Int = _.toInt | |
| override val from: (Int) => String = _.toString | |
| } | |
| } | |
| /** This will not behave as expected */ | |
| trait ImplicitIsomorphismsFail { | |
| implicit def impliedTo[A, B](a: A)(implicit iso: A <=> B): B = iso.to(a) | |
| implicit def impliedFrom[A, B](b: B)(implicit iso: A <=> B): A = iso.from(b) | |
| } | |
| trait ImplicitIsomorphismsSuccess { | |
| /** We only need one direction due to [[scalaz.Isomorphism.isoCommutative]] */ | |
| implicit def impliedIso[A, B](a: A)(implicit iso: A <=> B): B = iso.to(a) | |
| } | |
| object Foo extends ImplicitIsomorphismsFail with StringIntIso { | |
| // Do not compile | |
| // val x: StringValue = "asdf" | |
| // val y: String = x | |
| } | |
| object Bar extends ImplicitIsomorphismsSuccess with StringIntIso { | |
| val x: Int = "asdf" | |
| val y: String = x | |
| } | |
| object BarDesugar extends ImplicitIsomorphismsSuccess with StringIntIso { | |
| val x: Int = BarDesugar.impliedIso("asdf")(BarDesugar.StringIntIso) | |
| val y: String = BarDesugar.impliedIso(BarDesugar.x)(scalaz.Isomorphism.isoCommutative) | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment