Skip to content

Instantly share code, notes, and snippets.

@dwalend
Created June 5, 2015 02:26
Show Gist options
  • Select an option

  • Save dwalend/464a3c69c94165f02cd4 to your computer and use it in GitHub Desktop.

Select an option

Save dwalend/464a3c69c94165f02cd4 to your computer and use it in GitHub Desktop.

Revisions

  1. dwalend created this gist Jun 5, 2015.
    52 changes: 52 additions & 0 deletions InnerObjectVisibiltiy.Scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    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)
    }