5

I was writing a matrix class in Scala, and I thought the best way to implement a transpose operation would be to just return an interface with all the operations "transposed." So if matrix.apply(i, j) returns the (i, j)th element, then matrix.transpose returns an interface (but not a copy of the data) that contains an apply method that returns matrix(j, i). And I wrote that interface sort of like this (what I really wrote is much messier):

abstract class Matrix {
   def apply(i : Int, j : Int) : Double
   //other matrixy operations
   private def outer = this //so the inner can see the enclosing instance
   object TransposedInterface extends Matrix {
      def apply(i :Int, j : Int) = outer(j, i)
   }
}

Which is cute, I guess, but now TransposedInterface also has an object inside it called TransposedInterface, and so on, recursively, and where does it all end?

I tried the following in the interpreter:

class Outer(val i : Int) {
   object Inner extends Outer(i + 1)
}

val o = new Outer(1)
o.Inner.Inner.Inner.Inner.i

Which runs and evaluates to 5, like it should, I guess.

So what's actually going on? Is the inner object evaluated lazily? Is it garbage collect when it's not immediately being used, then instantiated again next time outer.Inner is called? Is it some voodoo that I haven't thought of?

kiritsuku
  • 52,967
  • 18
  • 114
  • 136
Peter Perez
  • 63
  • 1
  • 4

1 Answers1

3

It's instantiated lazily and will not be garbage collected until the outer class is collected, since the outer class contains a reference to it.

In general, object Foo { ... } acts very much like lazy val Foo = { ... }. Since objects cannot be null when valid but are certainly objects, they're more efficient (faster check for existence--just sees if the field is null) in this context, but have the drawback of requiring a second .class file. (You generally don't care about how many class files there are, so this is probably not a big deal.)

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
  • Thanks! And it turns out that knowing the answer makes it much easier to find [the answer](http://stackoverflow.com/questions/3448691/val-and-object-inside-a-scala-class). – Peter Perez Jul 23 '12 at 20:59