Scala:扩展内部类,而不引用外部类 [英] Scala: Extending inner class, without reference to outer class

查看:80
本文介绍了Scala:扩展内部类,而不引用外部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在外部类内部或从外部类派生的类内部扩展内部类/特征.我可以扩展外部类的特定实例的内部类,如下所示:

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 }

但这不会编译:

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

那么,是否要扩展外部特质/类中的内部类/特质而不引用外部特质/类?

我不希望在没有外部类实例仅声明其类型的情况下实例化派生的内部类.

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

推荐答案

您可以将特征与自类型做类似的事情.例如,假设我们有以下内容:

You can use a trait with a self-type to do something similar. Suppose for example that we have the following:

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

我们想在Inner中添加一些功能而又不使用Outer:

And we want to add some functionality to Inner without having an Outer around:

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

现在,当我们实例化Inner时,可以在MyInner中混合使用:

Now when we instantiate an Inner we can mix in 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

这不完全是您想要的,而是关闭.

It's not exactly what you want, but close.

这篇关于Scala:扩展内部类,而不引用外部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆