参考Scala中内部类的类型 [英] Referring to the type of an inner class in Scala
问题描述
以下代码试图模仿 DSL 的多态嵌入:它不是在 Inner
中给出行为,而是在其封闭类的 useInner
方法中编码.我添加了 enclosure
方法,这样用户只需保留对 Inner
实例的引用,但始终可以获取它们的封闭实例.通过这样做,来自特定 Outer
实例的所有 Inner
实例都只绑定到一个行为(但这里需要它).
The following code tries to mimic Polymorphic Embedding of DSLs: rather than giving the behavior in Inner
, it is encoded in the useInner
method of its enclosing class. I added the enclosing
method so that user has only to keep a reference to Inner
instances, but can always get their enclosing instance. By doing this, all Inner
instances from a specific Outer
instance are bound to only one behavior (but it is wanted here).
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 抱怨:
It does not compile and scala 2.8 complains about:
type mismatch; found: sandbox.Outer#Inner
required: _81.Inner where val _81:sandbox.Outer
来自编程Scala:嵌套类和Scala 之旅:内部类,在我看来问题在于 useInner
期望来自特定 Outer
实例的 Inner
实例作为参数.
From Programming Scala: Nested classes and A Tour of Scala: Inner Classes, it seems to me that the problem is that useInner
expects as argument an Inner
instance from a specific Outer
instance.
真正的解释是什么以及如何解决这个问题?
What is the true explanation and how to solve this problem ?
推荐答案
我想 Inner 类型就像 this.Inner 类型.Outer#Inner 独立于外部实例(不是路径依赖类型).
I suppose the type Inner is like the type this.Inner. Outer#Inner is independent of the outer instance (not a path-dependent type).
abstract class Outer {
sealed class Inner {
def enclosing = Outer.this
}
def useInner(x:Outer#Inner) : Boolean
}
def toBoolean(x:Outer#Inner) : Boolean = x.enclosing.useInner(x)
这篇关于参考Scala中内部类的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!