Created
June 5, 2015 02:26
-
-
Save dwalend/464a3c69c94165f02cd4 to your computer and use it in GitHub Desktop.
Code for a blog entry about inner objects and inner traits. This won't compile, but I think maybe it should.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait TopTrait { | |
def topDef:String | |
} | |
trait BeyondTrait { | |
def innerThing:InnerTrait | |
trait InnerTrait extends TopTrait{ | |
def innerDef = "innerDef" | |
def topDef = "topDef" | |
} | |
} | |
class Beyond extends BeyondTrait { | |
override def innerThing = new InnerTrait{ | |
def beyondDef = "innerThing from beyond" | |
} | |
} | |
class OuterClass(beyond: Beyond){ | |
//making beyond a val lets it work (because InnerTrait isn't private anymore.) | |
//class OuterClass(val beyond: Beyond){ | |
object InnerObject { | |
// this won't compile | |
// "private value beyond escapes its defining scope as part of type OuterClass.this.beyond.InnerTrait" | |
// the compiler won't walk up the tree to find TopTrait | |
// and it won't decide that it has access to the private beyond member | |
val innerThing = beyond.innerThing | |
// and innerThing won't be defined | |
val topDefResult = innerThing.topDef | |
val innerDefResult = innerThing.innerDef | |
// this will compile, cast up to TopTrait. innerDef is not available, but everything else works | |
// val innerThing:TopTrait = beyond.innerThing | |
//but this works as expected | |
// val innerDefResult = beyond.innerThing.innerDef | |
//as does this | |
// val topDefResult = beyond.innerThing.topDef | |
val comboResult = s"$innerDefResult and $topDefResult" | |
} | |
} | |
object ShowIt{ | |
println(new OuterClass(new Beyond()).InnerObject.comboResult) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment