你好,
在一个我无法修改代码的包里,类的层次结构如下。
class Outer:
class Inner(number: Int):
???
我想给 Inner 加个方便使用的包装,但因为 Inner 依赖外层实例,目前只做到把它放进外层类的子类里面。
new Outer:
case class InnerCase(number: Int) extends Inner(number):
???
(new InnerCase(3)).copy() // sample usage
可惜,在多个地方继承 Outer,就意味着每个新子类里都得重复这个方便使用的 case class。为了不反复复制定义,我希望有个类能用于任意 Outer#Inner。我试了下面的办法。
case class InnerCase(number: Int)(owner: Outer) extends owner.Inner(number):
???
new Outer:
host =>
InnerCase(3)(host).copy()(host)
new Outer:
host =>
val instance = InnerCase(4)(host).copy()(host)
val widened: Inner = instance // line causing trouble
但在需要 Inner 的地方多态地使用 InnerCase 时,会出现这个诊断。
Found: InnerCase
Required: Inner
我还是 Scala 新手,所以觉得应该有更好的办法实现这个目标。想必从类型理论上可以解释为什么直接这样做会违反类型系统。无论如何,很希望有人指点一下继承内部类的“正确”方法。
从英语翻译·查看原文Hi,
In a package whose code is outside my control, there is a hierarchy of classes arranged as follows:
class Outer:
class Inner(number: Int):
???
I'm trying to add a wrapper around Inner as a convenience, but because Inner depends on its enclosing instance, I've only managed to place it within a subclass of that enclosing class:
new Outer:
case class InnerCase(number: Int) extends Inner(number):
???
(new InnerCase(3)).copy() // sample usage
Unfortunately, subclassing Outer in several places means repeating that convenience case class inside each new subclass. To avoid repeatedly duplicating the definition, I'd prefer a class usable with an arbitrary Outer#Inner This is the solution I tried:
case class InnerCase(number: Int)(owner: Outer) extends owner.Inner(number):
???
new Outer:
host =>
InnerCase(3)(host).copy()(host)
new Outer:
host =>
val instance = InnerCase(4)(host).copy()(host)
val widened: Inner = instance // line causing trouble
But using an InnerCase polymorphically in a place requiring an Inner produces this diagnostic:
Found: InnerCase
Required: Inner
I'm still very much a beginner with Scala, so I imagine there must be a better way to achieve what I'm after here. Presumably there's a type-theoretic explanation for why my direct approach violates the type system. Either way, I'd really welcome pointers toward the “proper” approach to subclassing an inner class.