简体   繁体   English

什么是Scala'新'语法

[英]What is this Scala 'new' syntax

From the ScalaTest docs: 来自ScalaTest文档:

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? 这里创建的是一个匿名类,它是AnyRef的子类吗?

Yep, it returns instance of anynomous class. 是的,它返回任何类的实例。 It is not hard to check it by yourself in REPL session: 在REPL会话中自己检查它并不难:

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

Java can do the essentially same thing, believe it or not. 无论信不信,Java都能做同样的事情。 The following is valid Java 以下是有效的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. Java版本只是一种稍微冗长的语法,并且具有类型系统限制,使其几乎无用。 More about it here http://james-iry.blogspot.com/2009/04/java-has-type-inference-and-refinement.html 更多关于它http://james-iry.blogspot.com/2009/04/java-has-type-in​​ference-and-refinement.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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