Scala:如何模式匹配参数化类型的并集
我正在使用实现Scala中的非固定联合类型。我有以下课程:Scala:如何模式匹配参数化类型的并集,scala,Scala,我正在使用实现Scala中的非固定联合类型。我有以下课程: class Foo[T] { trait Contr[-A] {} type Union[A,B] = {type Check[Z] = Contr[Contr[Z]] <:< Contr[Contr[A] with Contr[B]]} def foo[U: Union[T,Foo[T]]#Check](x:U) = x match { case _: Foo[T] => print
class Foo[T] {
trait Contr[-A] {}
type Union[A,B] = {type Check[Z] = Contr[Contr[Z]] <:< Contr[Contr[A] with Contr[B]]}
def foo[U: Union[T,Foo[T]]#Check](x:U) = x match {
case _: Foo[T] => println("x is a Foo[T]")
case _: T @unchecked => println("x is a T")
}
}
然而:
val bar = new Foo[Foo[Int]]
bar.foo(bar) // OK: prints "x is a Foo[T]"
bar.foo(aux) // Not OK: prints "x is a Foo[T]"
有没有办法解决这个问题,也许还可以消除未选中的@
编辑
我认为对于这个特定的例子,Union
类型可以简化为:
type Union[Z] = Contr[Contr[Z]] <:< Contr[Contr[T] with Contr[Foo[T]]]
这使得代码更简单。但是,问题仍然存在。我提出了以下建议,这些建议似乎有效,并且更接近我的实际用例:
import scala.reflect.runtime.universe._
case class Foo[T](z:T)(implicit tt:TypeTag[T], ft:TypeTag[Foo[T]]) {
trait Contr[-A]
type Union[Z] = Contr[Contr[Z]] <:< Contr[Contr[T] with Contr[Foo[T]]]
def foo[U: Union](x:U)(implicit tu:TypeTag[U]):T = tu.tpe match {
case t if t =:= tt.tpe => x.asInstanceOf[T]
case t if t =:= ft.tpe => x.asInstanceOf[Foo[T]].z
}
}
不过,我很乐意去掉
x.asInstanceOf
。要删除@未选中的,请使用:case=>println(“x是T”)
def foo[U: Union](x:U) = ...
import scala.reflect.runtime.universe._
case class Foo[T](z:T)(implicit tt:TypeTag[T], ft:TypeTag[Foo[T]]) {
trait Contr[-A]
type Union[Z] = Contr[Contr[Z]] <:< Contr[Contr[T] with Contr[Foo[T]]]
def foo[U: Union](x:U)(implicit tu:TypeTag[U]):T = tu.tpe match {
case t if t =:= tt.tpe => x.asInstanceOf[T]
case t if t =:= ft.tpe => x.asInstanceOf[Foo[T]].z
}
}
val aux = new Foo[Int](42)
val bar = new Foo[Int](7)
val foobar = new Foo[Foo[Int]](bar)
println(aux.foo(aux)) // 42
println(aux.foo(1)) // 1
println(foobar.foo(aux)) // Foo(42)
println(foobar.foo(foobar)) // Foo(7)