引用Scala中内部类的类型
以下代码尝试模仿 DSL 的多态嵌入:而不是给出Inner
中的行为,它在其封闭类的 useInner
方法中进行编码。我添加了 enclosure
方法,以便用户只需保留对 Inner
实例的引用,但始终可以获取其封闭实例。通过这样做,来自特定 Outer
实例的所有 Inner
实例仅绑定到一种行为(但这里需要它)。
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
来自 Scala 编程:嵌套类 和 Scala 之旅:内部类,在我看来,问题在于useInner
期望来自特定 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)
It does not compile and scala 2.8 complains about:
type mismatch; found: sandbox.Outer#Inner
required: _81.Inner where val _81:sandbox.Outer
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想 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).
问题正如您所描述的,
useInner
需要特定Outer
实例的Inner
。由于enclosure
返回一个通用的Outer
,据我所知,确实没有办法将两者联系在一起。但是,您可以强制它:
The problem is as you describe, that
useInner
is expecting anInner
of a specificOuter
instance. Sinceenclosing
returns a genericOuter
, there is really no way to tie both together that I know of.You can force it, however:
你也可以这样定义你的成员:
或者你可以这样写:
You can also define your member like this:
Or you can write like this: