Scala: extending an inner class without referencing an outer class

I can extend the inner class / attribute inside the outer class or inside the class derived from the outer class. I can extend the inner class of a specific instance of the outer class, as in:

class Outer { class Inner{} } class OtherCl(val outer1: Outer) { class InnA extends outer1.Inner{} } 

Note: even this looks like a compilation, creating very interesting features:

 trait OuterA { trait InnerA } trait OuterB { trait InnerB } class class2(val outerA1: OuterA, val outerB1: OuterB) { class Inner2 extends outerA1.InnerA with outerB1.InnerB } 

But this does not compile:

 class OtherCl extends Outer#Inner 

As far as I can see, I'm trying to extend a parameterized class where the type parameter is an instance of an external class, so something similar to an action

 class OtherCl[T where T is instance of Outer] extends T.Inner 

Anyway, in order to expand the inner class / trait that is inside the outer trait / class without reference to the outer trait / class?

I am not trying to create an instance of a derived inner class without an instance of an outer class declaring only its type.

+4
source share
2 answers

You can use the dash with autotype to do something like this. Suppose, for example, that we have the following:

 class Outer(val x: Int) { class Inner { def y = x } } 

And we want to add some features to Inner without having an Outer around:

 trait MyInner { this: Outer#Inner => def myDoubledY = this.y * 2 } 

Now that we create an Inner instance, we can mix in MyInner :

 scala> val o = new Outer(21) o: Outer = Outer@72ee303f scala> val i = new o.Inner with MyInner i: o.Inner with MyInner = $anon$1@2c7e9758 scala> i.myDoubledY res0: Int = 42 

This is not exactly what you want, but close.

+8
source

Not quite what you are looking for, but with a path-dependent type (available at 2.10 or 2.9 using the -Ydependent-method-types flag, which you can do:

 class Outer { class Inner {}; def create = new Inner } def foo[T <: Outer](x: T) = x.create 

Hope that helps

+3
source

All Articles