【发布时间】:2021-06-30 12:19:27
【问题描述】:
考虑以下示例:
我。
class A
class B
sealed trait Test {
type Meta
}
case class Test1() extends Test {
type Meta = A
}
case class Test2() extends Test {
type Meta = B
}
case class Info[T <: Test](t: T, m: T#Meta)
//Filters List[Info[_ <: Test]] by a generic type T <: Test and returns List[Info[T]]
def filter[T <: Test: ClassTag](lst: List[Info[_ <: Test]])(
implicit ev: ClassTag[T#Meta]): List[Info[T]] =
lst.collect {
case Info(t: T, a: T#Meta) =>
val i: Info[T] = Info[T](t, a)
i
}
让我陷入困境的是PartialFunction 的case 是否详尽无遗。我尝试完全模式匹配Info[_ <: Test],如下所示:
二。
val t: Info[_ <: Test] = ???
t match {
case Info(t: Test1, a: Test1#Meta) =>
println("1")
case Info(t: Test2, a: Test2#Meta) =>
println("2")
}
并收到以下(非常可怕的)警告:
match may not be exhaustive.
It would fail on the following inputs:
Info((x: _$2 forSome x not in (Test1, Test2)), (x: _$2#Meta forSome x not in (A, B))),
Info((x: _$2 forSome x not in (Test1, Test2)), ??), Info((x: _$2 forSome x not in (Test1, Test2)), A()),
Info((x: _$2 forSome x not in (Test1, Test2)), B()), Info(??, (x: _$2#Meta forSome x not in (A, B))),
Info(Test1(), (x: _$2#Meta forSome x not in (A, B))),
Info(Test1(), B()), Info(Test2(), (x: _$2#Meta forSome x not in (A, B))),
Info(Test2(), A())
问题:在这种情况下的filter 实现是否我在语义方面是正确的还是遗漏了一些奇怪的cases ?
【问题讨论】:
-
另请注意,在第一节中,
collect函数中的match不必是详尽的match,因为不匹配的元素将被过滤掉.
标签: scala generics type-safety