Skip to content

Instantly share code, notes, and snippets.

@soujiro32167
Created December 4, 2022 19:41
Show Gist options
  • Save soujiro32167/827df0b239d913ed9ce5e9ba5628a9c8 to your computer and use it in GitHub Desktop.
Save soujiro32167/827df0b239d913ed9ce5e9ba5628a9c8 to your computer and use it in GitHub Desktop.
Scala 3: Matching on member of a union types
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))
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