我正在尝试使用依赖方法类型和编译器的夜间构建(2.10.0.r26005-b20111114020239)来抽象模块中的case类。我从Miles Sabin' example那里找到了一些灵感。
我真的不明白下面的(自包含的)代码出了什么问题。输出取决于foo中模式的顺序。
// afaik, the compiler doesn't not expose the unapply method
// for a companion object
trait Isomorphic[A, B] {
def apply(x: A): B
def unapply(x: B): Option[A]
}
// abstract module
trait Module {
// 3 types with some contraints
type X
type Y <: X
type Z <: X
// and their "companion" objects
def X: Isomorphic[Int, X]
def Y: Isomorphic[X, Y]
def Z: Isomorphic[Y, Z]
}
// an implementation relying on case classes
object ConcreteModule extends Module {
sealed trait X { val i: Int = 42 }
object X extends Isomorphic[Int, X] {
def apply(_s: Int): X = new X { }
def unapply(x: X): Option[Int] = Some(x.i)
}
case class Y(x: X) extends X
// I guess the compiler could do that for me
object Y extends Isomorphic[X, Y]
case class Z(y: Y) extends X
object Z extends Isomorphic[Y, Z]
}
object Main {
def foo(t: Module)(x: t.X): Unit = {
import t._
// the output depends on the order of the first 3 lines
// I'm not sure what's happening here...
x match {
// unchecked since it is eliminated by erasure
case Y(_y) => println("y "+_y)
// unchecked since it is eliminated by erasure
case Z(_z) => println("z "+_z)
// this one is fine
case X(_x) => println("x "+_x)
case xyz => println("xyz "+xyz)
}
}
def bar(t: Module): Unit = {
import t._
val x: X = X(42)
val y: Y = Y(x)
val z: Z = Z(y)
foo(t)(x)
foo(t)(y)
foo(t)(z)
}
def main(args: Array[String]) = {
// call bar with the concrete module
bar(ConcreteModule)
}
}有什么想法吗?
发布于 2011-11-22 18:25:24
这些警告是正确的,也是意料之中的,因为从foo内部来看,Y和Z都将被擦除到它们的边界,即。X。
更令人惊讶的是,无论是与Y的比赛还是与Z的比赛,都会挫败与X的比赛。在这种情况下,
def foo(t: Module)(x: t.X): Unit = {
import t._
// the output depends on the order of the first 3 lines
// I'm not sure what's happening here...
x match {
// unchecked since it is eliminated by erasure
// case Y(_y) => println("y "+_y)
// unchecked since it is eliminated by erasure
// case Z(_z) => println("z "+_z)
// this one is fine
case X(_x) => println("x "+_x)
case xyz => println("xyz "+xyz)
}
}结果是,
x 42
x 42
x 42这似乎是合理的,而随着其中一场比赛的恢复,
def foo(t: Module)(x: t.X): Unit = {
import t._
// the output depends on the order of the first 3 lines
// I'm not sure what's happening here...
x match {
// unchecked since it is eliminated by erasure
case Y(_y) => println("y "+_y)
// unchecked since it is eliminated by erasure
// case Z(_z) => println("z "+_z)
// this one is fine
case X(_x) => println("x "+_x)
case xyz => println("xyz "+xyz)
}
}结果是,
xyz AbstractMatch$ConcreteModule$X$$anon$1@3b58fa97
y AbstractMatch$ConcreteModule$X$$anon$1@3b58fa97
xyz Z(Y(AbstractMatch$ConcreteModule$X$$anon$1@3b58fa97))但事实并非如此:我看不出为什么额外的情况会导致选择xyz而不是X,所以我认为您在模式匹配器中遇到了错误。我建议你在Scala JIRA中搜索类似的问题,如果你找不到一个,打开一个从上面提取的最小化再现示例的工单。
老实说,在上面的第二个示例中,我本以为在所有三个实例中都选择了Y大小写,这要归功于Y被擦除为X,以及匹配表达式中X大小写之前的Y大小写。但我们在这里是不受约束的领域,我对我的直觉不是百分之百有信心。
https://stackoverflow.com/questions/8208539
复制相似问题