Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this Scala 'new' syntax

Tags:

scala

From the ScalaTest docs:

class ExampleSpec extends FlatSpec {

def fixture =
new {
  val builder = new StringBuilder("ScalaTest is ")
  val buffer = new ListBuffer[String]
}

...

I don't understand how the new keyword is being used here. fixture is obviously a function, which declares and returns... what? It seems to be an object, since it has members (builder & buffer) that can be accessed with . notation.

Is what is being created here an anonymous class that is a subclass of AnyRef?

like image 442
Scala Newb Avatar asked May 29 '13 15:05

Scala Newb


1 Answers

Yep, it returns instance of anynomous class. It is not hard to check it by yourself in REPL session:

scala> def fixture = new { val string = "mr. String" }
fixture: Object{val string: String}

Java can do the essentially same thing, believe it or not. The following is valid Java

(new Object() {   
  public void sayHello() {
    System.out.println("hello!");   
  }   
}).sayHello(); 

The Java version is just a mildly more verbose syntax and has a type system limitation that makes it mostly useless. More about it here http://james-iry.blogspot.com/2009/04/java-has-type-inference-and-refinement.html

like image 70
om-nom-nom Avatar answered Nov 02 '22 23:11

om-nom-nom