Scala and Java inner class

The path dependent types

 

 

 

In scala, you can have abstract types, which will be instantiated/specialized in subclasses. such as follow.

 

 

 

class Outter {
  class Inner { 
  }
}


 

and in the repl, you type

 

 

val o1 = new  Outer
val o2 = new Outer


new o1.Inner
resl1: o1.Inner = Outter$Inner@ldf6ed6
 

the resulting inner object will contain a reference to its outer object, the object references from o1.  Because the type Outer#Inner does not name any specific instance of outer, you can't create an instance of it

 

 

 

scala > new Outer#Inner
<Console> 7 : error : outer is not a legal prefix for a constructor 
             new Outer#Inner

 

 

 

so that means that in scala because the type can be an abstract member of an abstract class, Object.InnerType has a concrete type, while the static class notation, Outer.Iner may/may not have the necessary type information.

 

the Outer#Inner notation is much like the java Outer.Inner notation, let's take a close look at how the java nested class works.

 

The magic Outer.this   symbol

 

 

 

 

since it is a rule that the inner class can access the outer class's instance. but this requires a bit, since it is highly possible that the inner may have a member which has the same field as the outer class.

 

how to disambiguate the inner class and the outer class? here is an example.

 

 

 

 

 

public class InnerClassTest {
	public static void main(String[] args) {
		new OutterClass().doIt();
	}
}

class OutterClass {
	
	
	private String m_outterClassMember = null;
	
	
	public OutterClass() {
		m_outterClassMember = "Hello world";
	}
	
	public void doIt() {
		new InnerClass().sayHello();
	}
	
	
	public void enclosingClassMethod(String arg) {
		System.out.println(arg);
	}
	
	class InnerClass {
		
		public void sayHello() {
			OutterClass.this.enclosingClassMethod(OutterClass.this.m_outterClassMember);
		}
	}
}
 

 

你可能感兴趣的:(Scala and Java inner class)