One of the exciting features of Scala 3 is union types. This opinion is shared by many people according to a recent presentation by Martin Odersky at Scala Days.
I made a simple test of my naive expectations of how union types would would, and was disappointed that they don’t seem to do the magic I had hoped.
I prepared a Scastie with the code which I hoped would work. But alas it does not.
In the code I define 5 methods named
Foo with the following signatures:
Then I tried to evaluate
List(1, MyClass(2), 3, MyClass(4),5,6).fold(MyClass(0))(MyClass.Foo). I was hoping the type of
List(1, MyClass(2), 3, MyClass(4),5,6).fold(MyClass(0)) would be
List[Int|MyClass] so that at least the 5th of the Foo methods would be applicable.
Instead, I got the compiler error.
Am I expecting completely the wrong behavior from union types?
None of the overloaded alternatives of method Foo in object MyClass with types (a: Int | MyClass, b: Int | MyClass): MyClass (b1: MyClass, b2: MyClass): MyClass (a1: Int, a2: Int): MyClass (b: MyClass, a: Int): MyClass (a: Int, b: MyClass): MyClass match expected type (A1, A1) => A1