下面的代码试图模仿DSLs 的多态嵌入:它没有给出 in 中的行为,而是在其封闭类Inner
的方法中编码。useInner
我添加了该enclosing
方法,以便用户只需保留对Inner
实例的引用,但始终可以获取它们的封闭实例。通过这样做,Inner
来自特定Outer
实例的所有实例都只绑定到一种行为(但这里需要它)。
abstract class Outer {
sealed class Inner {
def enclosing = Outer.this
}
def useInner(x:Inner) : Boolean
}
def toBoolean(x:Outer#Inner) : Boolean = x.enclosing.useInner(x)
它不编译并且 scala 2.8 抱怨:
type mismatch; found: sandbox.Outer#Inner
required: _81.Inner where val _81:sandbox.Outer
从Programming Scala: Nested classes和A Tour of Scala: Inner Classes中,在我看来,问题在于期望来自特定实例useInner
的实例作为参数。Inner
Outer
什么是真正的解释以及如何解决这个问题?