简体   繁体   English

scala-在外部类构造函数中引用内部类类型

[英]scala - Referencing inner class type in outer class constructor

I would like to access inner class type in the outer constructor, like : 我想访问外部构造函数中的内部类类型,例如:

// does not compile, MyInner now know from outer constructor
class MyOuter(private val mySet: Set[MyInner]) {
  class MyInner(index: Int)
}

The Inner class must be non static (outside an object) as it may access some fields of the outer class instance. 内部类必须是非静态的(在对象外部),因为它可以访问外部类实例的某些字段。

The code below compiles, but the field is mutable: 下面的代码可以编译,但是该字段是可变的:

class MyOuter() {
  class MyInner(index: Int)

  private var mySet: Set[MyInner] = _
  def this(_mySet: Set[MyInner]) {
    this()
    mySet = _mySet
  }

This seems to be scala-specific as the below Java code is legal: 这似乎是scala特定的,因为以下Java代码是合法的:

import java.util.Set;

public class Outer {

    private final Set<Inner> mySet;

    public class Inner {
        private final int index;

        public Inner(int _index) {
            index = _index;
        }
    }

    public Outer(Set<Inner> _mySet) {
        this.mySet = _mySet;
    }

}

Thanks for your help 谢谢你的帮助

This phrase: "The Inner class must be non static (outside an object) as it may access some fields of the outer class instance." 这句话:“内部类必须是非静态的(在对象外部),因为它可以访问外部类实例的某些字段。” explains why what you want is impossible: you are trying to create an instance of a class, that accesses fields of an instance of another class, that does not yet exist . 解释了为什么您想要的东西是不可能的:您正在尝试创建一个类的实例,该实例访问另一个类的实例的字段,而该字段尚不存在

And no, it would not work in java either. 不,它在Java中也不起作用。 Note the static qualifier in the answer to the question you referenced in your comment. 注意您在注释中引用的问题的答案中的static限定词。 It has the same effect as moving your inner class to a companion object - static inner classes in java can only access static members of the outer class. 它与将内部类移动到伴随对象的效果相同-Java中的静态内部类只能访问外部类的静态成员。

This would, I think, be the right solution for your case - make a companion object, and move the inner class there. 我认为,这将是适合您的情况的正确解决方案-制作一个伴随对象,然后将内部类移到那里。 No, you do not need to access members of the instance, that has not been constructed yet :) 不,您不需要访问尚未构造的实例成员:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM