这是什么Scala语法的语法?

What kind of syntax of Scala syntax is this?

我知道 Scala 的基本语法,但在下面的代码中,我不明白 describeit 结构在做什么。它们是某种匿名函数还是什么?

class SentimentAnalyzerSpec extends FunSpec with Matchers {

  describe("sentiment analyzer") {

    it("should return POSITIVE when input has positive emotion") {
      val input = "Scala is a great general purpose language."
      val sentiment = SentimentAnalyzer.mainSentiment(input)
      sentiment should be(Sentiment.POSITIVE)
    }
  }
}

这是 ScalaTest 通过 FunSuite.

提供的基本 DSL(领域特定语言)

describe 是一种方法,通过多参数列表接受 String 和 returns Unit 的名称值:

protected def describe(description: String)(fun: => Unit) {
    registerNestedBranch(description, None, fun, "describeCannotAppearInsideAnIt", sourceFileName, "describe", 4, -2, None)
}

它只是使用中缀表示法,这就是它看起来半 "magical" 的原因。

it 是一个包含名为 ItWord 的 class 的值。它有一个 apply 方法,它只是将您提供的方法注册为测试:

/**
* Supports test (and shared test) registration in <code>FunSpec</code>s.
* This field supports syntax such as the following:
* it("should be empty")
* it should behave like nonFullStack(stackWithOneItem)
*/
protected val it = new ItWord

protected class ItWord {
  def apply(specText: String, testTags: Tag*)(testFun: => Unit) {
    engine.registerTest(specText, Transformer(testFun _), "itCannotAppearInsideAnotherItOrThey", sourceFileName, "apply", 3, -2, None, None, None, testTags: _*)
  }
}

这些只是从 mixin traits 继承的方法和变量。您可以自己做类似的事情:

trait MyDsl {
  def bar(n: Int) = 123
  def foo(s: String)(d: String) = 234
}

所以如果你混在另一个class中,你可以写

class MyClass1 extends MyDsl {
  bar(foo("hello")("hi"))
}

(注意foo是多参数列表函数,Java中没有)

因为 Scala 允许您通过 中缀表示法省略括号 ( 可能会被省略并替换为 { 以对参数表达式进行分组。于是就变成了:

class MyClass1 extends MyDsl {
  bar {
    foo("hello") {
      "hi"
    }
  }
}

现在,所有这些定义实际上都发生在 MyClass1

的主构造函数中