我遇到了一個場景,在嘗試創建內部類的實體時出現編譯錯誤“無法決議符號#INNER_CLASS_NAME” 。
請注意,只有當我創建別名來參考封閉外部類的參考時,我才會收到此錯誤。
請參閱下面的代碼片段以獲取更多詳細資訊:
package netsting
object nested_class4 extends App {
class Network(val name: String) {
class Member(val name: String) {
def description = s"Inner class field name :${Network.this.name}, outer name : ${this.name} "
}
}
class Network2(val name: String) { outer => {
class Member2(val name: String) {
def description = s"Inner class field name :${outer.name}, outer name : ${this.name} "
}
}
}
val net1 = new Network("net1")
val mem1 = new net1.Member("mem1")
// TODO : How to create instance of inner class while using alias name reference for enclosing class instance
val net2 = new Network2("net1")
val mem2 = new net2.Member2("mem1")
println(mem2.description)
}
在這里,在上面的示例中,我能夠創建內部類Network#Member的實體而不會出現任何錯誤。但是,我在嘗試創建內部類Network2#Member2的實體時遇到編譯錯誤。

Here, the compilation error goes away if I remove the alias name "outer" and just use the casual way Network.this.name to refer to enclosing class fields.
What is the correct way to create instance of inner class when we have created alias name to refer to this reference of outer class ?
uj5u.com熱心網友回復:
“別名”的語法不包括任何額外的大括號:
class Network2(val name: String) { outer => // MUST be like this
class Member2(val name: String) {
def description = s"Inner class field name: ${outer.name}, outer name: ${this.name}"
}
}
// WRONG
class Network2Bad(val name: String) { outer => { ??? } }
// same as
// class Network2Bad(val name: String) { { ??? } }
// the body of this class consists of a block expression { ??? }
// which is evaluated whenever a Network2Bad is constructed
// by ordinary scoping rules, nothing declared in that block is declared in the enclosing scope (the Network2Bad object)
val net2 = new Network2("net2")
val mem2 = new net2.Member2("mem2")
println(mem2.description)
PS我所知道的唯一官方名稱是“別名”是“自我型別”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/440179.html
下一篇:狀態函式內部的迭代器為空
