通过类型参数对ADT列表进行类型安全过滤
考虑以下示例:
一世。
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
}
SCASTIE 演示
让我陷入困境的事情是PartialFunction'scase是否详尽无遗。我试图完全模式匹配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")
}
SCASTIE 演示
并收到以下(非常可怕的)警告:
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在我在语义方面纠正或case遗漏了一些奇怪的s的情况下,实施是否正确?
回答
好吧,正如您所看到的,您有一个建议的破坏案例列表。例如,Info(Test1(), B())。让我们构建其中之一。
与 中的路径相关类型不同def foo(t: Test)(meta: t.Meta) = ???,使用它们时的类型投影case class Info不会对 的含义进行编码T = Test1 => T#Meta = A。尽管我需要一个简单的实用方法来说服 scalac 推断出我想要的类型。
def castMeta[T <: Test](t: T#Meta): Test#Meta = t
有了它,我们就可以从 A 和 B 中获取键入为 Test#Meta 的值。
所以,
val t: Info[_ <: Test] = Info[Test](Test1(), castMeta[Test2](new B))
将MatchError在运行时导致 a ,并使其不涉及任何“黑客”,如空值、asInstanceOfs 或ClassTags。
另请注意,Type#Member由于稳健性问题,计划在 Scala 3 中删除表单的一般类型投影。
编辑:请注意,您的过滤器可能会执行您想要的操作,因为您自己提供了目标类型对,只是您的模型完全允许 scalac 警告您的奇怪情况:)