Dan Halbert
Dan Halbert

Reputation: 2916

What is this Scala syntax called: new C { i = 5 } // there's a block after the new

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.

Upvotes: 2

Views: 207

Answers (1)

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 59994

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.

Upvotes: 9

Related Questions