简体   繁体   中英

What is this Scala 'new' syntax

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM