How to refer to an outer object from an inner class in Scala
Consider this code (which is a type of safe units):
abstract class UnitsZone {
type ConcreteUnit <: AbstractUnit
abstract class AbstractUnit(val qty: Int) {
SOME_ABSTRACT_MEMBERS
def +(that: ConcreteUnit): ConcreteUnit = POINT_OF_INTEREST.apply(this.qty + that.qty)
def apply(param: Int) = SOME_IMPLEMENTATION
}
def apply(qty: Int): ConcreteUnit
}
object Imperial extends UnitsZone {
type ConcreteUnit = Pound
class Pound(override val qty: Int) extends AbstractUnit(qty) {
CONCRETE_MEMBERS_HERE
}
def apply(qty: Int) = new Pound(qty)
}
To do all this, I need to call a method of apply
an external object regarding inheritance (marked as POINT_OF_INTEREST in the above code). With this in mind, I dare to ask a few questions:
- Is there a way to do this?
- If there are many, what are the pros and cons for each?
- If you think this is all wrong, what is your correct way to implement such functionality?
+3
Artem Pyanykh
source
to share
2 answers
Use your own link:
abstract class UnitsZone {
outer =>
type ConcreteUnit <: AbstractUnit
...
abstract class AbstractUnit(val qty: Int) {
def +(that: ConcreteUnit): ConcreteUnit = outer.apply(this.qty + that.qty)
...
}
}
See chapter 17. Self-referenced SO Scala tutorial for more information on what else this construct can do.
+7
kiritsuku
source
to share
Just like Java,
class Foo {
val foot = 0
class Bar {
val bart = Foo.this.foot
}
}
or Scala,
class Foo { self =>
val foot = 0
class Bar {
val bart = self.foot
}
}
+3
Ryoichiro Oka
source
to share