引用Scala中内部类的类型 [英] Referring to the type of an inner class in Scala
问题描述
以下代码试图模仿 DSL的多态嵌入:而不是在Inner
中给出行为,而是在其封闭类的useInner
方法中对其进行编码.我添加了enclosing
方法,以便用户仅需保留对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:嵌套类和
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屋!