This page is no longer maintained — Please continue to the home page at www.scala-lang.org

How to get access to the enclosing object of an inner class instance, from outside the class?

1 reply
Ken McDonald
Joined: 2011-02-13,
User offline. Last seen 42 years 45 weeks ago.
Here's an edited snippet of the code I'm working with:
abstract class Fragment { class Start extends Marker { def fragment: Fragment = Fragment.this } class End extends Marker { def fragment: Fragment = Fragment.this } }
When I first wrote this, I didn't put in the "def fragment" methods. But then I ran into the situation where I had a marker:
    val marker = aFragment.createStartMarker
and I realized I had no idea how to obtain a reference to 'aFragment' from 'marker'. I tried stuff along the lines of "marker.Fragment.this", but couldn't seem to find the magical invocation. So I defined the "fragment" methods to do the deed.
But I'd like to know how to get that reference without requiring an extra method to do it.
Thanks,Ken
Sebastien Bocq
Joined: 2008-12-18,
User offline. Last seen 42 years 45 weeks ago.
Re: How to get access to the enclosing object of an inner class
        abstract class Fragment { outer =>
class Start extends Marker { def fragment: Fragment = outer
                } class End extends Marker { def fragment: Fragment = outer } }
Hope this helps,
Sebastien

2011/5/18 Ken McDonald <ykkenmcd@gmail.com>
Here's an edited snippet of the code I'm working with:
abstract class Fragment { class Start extends Marker { def fragment: Fragment = Fragment.this } class End extends Marker { def fragment: Fragment = Fragment.this } }
When I first wrote this, I didn't put in the "def fragment" methods. But then I ran into the situation where I had a marker:
    val marker = aFragment.createStartMarker
and I realized I had no idea how to obtain a reference to 'aFragment' from 'marker'. I tried stuff along the lines of "marker.Fragment.this", but couldn't seem to find the magical invocation. So I defined the "fragment" methods to do the deed.
But I'd like to know how to get that reference without requiring an extra method to do it.
Thanks,Ken

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland