Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

Referring to the type of an inner class in Scala

The following code tries to mimic Polymorphic Embedding of DSLs: rather than giving the behavior in Inner, it is encoded in the useInner method of its enclosing class. I added the enclosing method so that user has only to keep a reference to Inner instances, but can always get their enclosing instance. By doing this, all Inner instances from a specific Outer instance are bound to only one behavior (but it is wanted here).

abstract class Outer {
  sealed class Inner {
    def enclosing = Outer.this
  }
 def useInner(x:Inner) : Boolean
}

def toBoolean(x:Outer#Inner) : Boolean = x.enclosing.useInner(x)

It does not compile and scala 2.8 complains about:

type mismatch; found: sandbox.Outer#Inner
               required: _81.Inner where val _81:sandbox.Outer

From Programming Scala: Nested classes and A Tour of Scala: Inner Classes, it seems to me that the problem is that useInnerexpects as argument an Inner instance from a specific Outer instance.

What is the true explanation and how to solve this problem ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suppose the type Inner is like the type this.Inner. Outer#Inner is independent of the outer instance (not a path-dependent type).

abstract class Outer {
  sealed class Inner {
    def enclosing = Outer.this
  }
  def useInner(x:Outer#Inner) : Boolean
}

def toBoolean(x:Outer#Inner) : Boolean = x.enclosing.useInner(x)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...