2

I encountered this syntax in someone else's Scala code, and don't remember reading about it:

val c  = new C { i = 5 }

It appears that the block after the new C is equivalent to:

val c = new C
c.i = 5

assuming a class definition like:

class C {
  var ii = 1
  def i_=(v: Int) { ii = v }
  def i = ii
}

What is this syntax called in Scala? I want to read more about it, but I can't find it described in Programming in Scala or elsewhere.

Dan Halbert
  • 2,761
  • 3
  • 25
  • 28

1 Answers1

9

You are instantiating an anonymous subclass of C.

It is not equivalent to the code you've shown — try calling getClass on the two instances called c in your snippets.

Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
  • Got it. The original code is just using that syntax to compactly initialize a Swing widget; the subclassing is not vital. – Dan Halbert Sep 12 '11 at 19:35
  • This idiom is mentioned in the SO "Hidden Features of Scala" [here](http://stackoverflow.com/questions/1025181/hidden-features-of-scala/6661607#6661607). – Dan Halbert Sep 13 '11 at 14:54