Search code examples
scalascala-cats

Cats typeclass for isomorphic types


What cats typeclass should I use to encode that two types are Isomorphic (i.e. can be converted back and forth without effects)

I want to encode the decomposition of a type into a tuple of two others: A <=> (B, C)

Obviously, the typeclass should expose the two functions for each direction of the conversion, and ideally implicit methods for convenient conversion. Something like this: (but failed to find it)

trait Iso[A,B] {
  def to(a: A):B
  def from(b: B): A
}

Solution

  • Are you looking for cats.evidence.Is?

    type A
    type B
    
    type X = Is[A, B] // A Is B
    
    val a: A = ???
    val b: B = ???
    val x: A Is B = ???
    val y: B Is A = ???
    
    x.coerce(a): B
    y.coerce(b): A
    

    It's similar to scalaz.Leibniz.