本文介绍了我可以在与外部类不同的文件中声明内部类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来声明内部类,它可以访问外部作用域(包装类).这两个类都非常庞大,所以我想在不同的文件中声明它们.例如我想做这样的事情:

I am looking for a way to declare inner class in a way it has access to outer scope (wrapping class). Both classes will be pretty huge so I want to declare them in different files. For example I would like to do something like:

A.scala:

class A(_secret:Int){
    val secret = _secret
    var clazz:Class = null
}

B.scala:

A.clazz = class B{
    def getSecret(){
        A.secret
    }
}

整个目的是避免将 this 作为构造函数参数向下传递,即.e.var clazz = new B(this).

The whole purpose is to avoid passing this as a constructor parameter down, i. e. var clazz = new B(this).

推荐答案

本身可能不是答案,但通常反之亦然:

Probably not an answer per se, but usually you do vice versa:

A.scala:

class A{
    type clazz = B
}

B.scala:

class B{

}

trait Foo { self: Bar => 
    def fooSecret = "foo secret"

    def foo() {
        println("I'm foo, but also know bar's secrets: " + self.barSecret)
    }
}

trait Bar { self: Foo =>
    def barSecret = "bar secret"

    def bar() {
        println("I'm bar, but also know foo's secrets: " + self.fooSecret)
    }
}

class Impl extends Foo with Bar
val x = new Impl
x.foo()
x.bar()

导致

I'm foo, but also know bar's secrets: bar secret
I'm bar, but also know foo's secrets: foo secret

请注意,我使用了 def 和不同的方法名称(在混入过程中很重要,因为涉及到继承)

Note that I used def's and different method names (it is important during mixing-in, since inheritance involved)

这篇关于我可以在与外部类不同的文件中声明内部类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 12:21