Created
December 4, 2022 19:41
-
-
Save soujiro32167/827df0b239d913ed9ce5e9ba5628a9c8 to your computer and use it in GitHub Desktop.
Scala 3: Matching on member of a union types
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
inline def f2[A, B](x: A | B): String = | |
x match | |
case a: A => "a" | |
case b: B => "b" | |
// doesn't work with subtyping | |
trait T[A] { | |
def foo(a: A): String | |
} | |
class Union[A, B](ta: T[A], tb: T[B]) extends T[A | B]{ | |
inline def foo(a: A | B): String = a match | |
case a: A => ta.foo(a) | |
case b: B => tb.foo(b) | |
} | |
def t[A] = new T[A]{ def foo(a: A): String = a.toString } | |
val union = new Union(t[String], t[Int]) | |
println(union.foo("foo")) | |
println(union.foo(1)) |
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 scala.reflect.Typeable | |
def f[A: Typeable, B: Typeable](x: A | B): String = | |
x match | |
case a: A => "a" | |
case b: B => "b" | |
// works with subtyping | |
trait T[A] { | |
def foo(a: A): String | |
} | |
class Union[A: Typeable, B: Typeable](ta: T[A], tb: T[B]) extends T[A | B]{ | |
def foo(a: A | B): String = a match | |
case a: A => ta.foo(a) | |
case b: B => tb.foo(b) | |
} | |
def t[A] = new T[A]{ def foo(a: A): String = a.toString } | |
val union = new Union(t[String], t[Int]) | |
println(union.foo("foo")) | |
println(union.foo(1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment