scalagenericsshapelessunion-types

Does shapeless for Scala 2 has analogue for Scala 3 union types?


Scala 3 has very convenient Union types. I'm looking for something closer in shapeless for Scala 2 that would allow similar behavior. Example:

case class Cs1()
case class Cs2()

I tried shapeless.v, but it does not seem to work as I thought it to.

val v: Cs1 v Cs2 = Cs1() // compile error

The error:

[error]  found   : example.Hello.Cs1
[error]  required: example.Hello.Cs1 ∨ example.Hello.Cs2

Is there something in shapeless for that?


Solution

  • shapeless.∨ is for context bounds, you can't use it in return type.

    def foo[T: (Cs1 |∨| Cs2)#λ] = ???
    
    foo[Cs1] // compiles
    foo[Cs2] // compiles
    foo[Int] // doesn't compile
    

    See also

    How to define "type disjunction" (union types)?

    Shapeless type disjunction for more then 2 types

    https://milessabin.com/blog/2011/06/09/scala-union-types-curry-howard/