4

I can extend an inner class/trait inside the outer class or inside a class derived from the outer class. I can extend an inner class of a specific instance of an outer class as in:

class Outer
{
  class Inner{}
}

class OtherCl(val outer1: Outer)
{
  class InnA extends outer1.Inner{}
}

Note: even this seems to compile fine producing very interesting possibilities:

trait OuterA
{ trait InnerA } 

trait OuterB
{ trait InnerB }

class class2(val outerA1: OuterA, val outerB1: OuterB)
{ class Inner2 extends outerA1.InnerA with outerB1.InnerB }

But this won't compile:

class OtherCl extends Outer#Inner

As far as I can see I'm trying to extend a parametrised class where the type parameter is an instance of the outer class so something to the effect of

class OtherCl[T where T is instance of Outer] extends T.Inner

So is the anyway to extend an inner class/ trait that's inside an outer trait/class without reference to the outer trait/class?

I am not looking to instantiate the derived inner class without an instance of the outer class only declare its type.

4

2 回答 2

9

您可以使用具有自我类型的特征来做类似的事情。例如,假设我们有以下内容:

class Outer(val x: Int) {
  class Inner {
    def y = x
  }
}

我们想在Inner没有Outer周围的情况下添加一些功能:

trait MyInner { this: Outer#Inner =>
  def myDoubledY = this.y * 2
}

现在,当我们实例化 an 时,Inner我们可以混入MyInner

scala> val o = new Outer(21)
o: Outer = Outer@72ee303f

scala> val i = new o.Inner with MyInner
i: o.Inner with MyInner = $anon$1@2c7e9758

scala> i.myDoubledY
res0: Int = 42

这不是您想要的,但很接近。

于 2012-06-09T21:12:35.467 回答
3

不完全是您要查找的内容,但具有路径相关类型(可在 2.10 或 2.9 上使用 -Ydependent-method-types 标志,您可以执行以下操作:

class Outer { class Inner {}; def create = new Inner }
def foo[T <: Outer](x: T) = x.create

希望有帮助

于 2012-06-09T20:36:07.030 回答