ogen
ogen

Reputation: 792

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:

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

Upvotes: 1

Views: 926

Answers (1)

Dima
Dima

Reputation: 40500

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. Note the static qualifier in the answer to the question you referenced in your comment. 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.

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 :)

Upvotes: 1

Related Questions