【发布时间】:2012-01-02 18:12:37
【问题描述】:
我正在尝试使用依赖方法类型和编译器的夜间构建 (2.10.0.r26005-b20111114020239) 来抽象模块中的案例类。我从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)
}
}
有什么想法吗?
【问题讨论】:
-
我刚刚尝试了最新的主干,但它不能为我编译:35:错误:非法依赖方法类型。使用 2.10.0.r26037-b20111121020211。它可能不适合工作?
-
刚刚用 2.10.0.r26037-b20111121020211 进行了测试,它可以为我编译。我复制粘贴了整个块,然后
Main.main(Array())。
标签: scala types pattern-matching type-erasure dependent-method-type