简体   繁体   English

这是什么样的Scala语法语法?

[英]What kind of syntax of Scala syntax is this?

I know the basic syntax of Scala, but in the following code, I don't understand what the describe and it constructs are doing. 我知道斯卡拉的基本语法,但在下面的代码,我不明白的是什么describeit构建在做什么。 Are they some kind of anonymous functions or what? 他们是某种匿名功能还是什么?

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)
    }
  }
}

This is the basic DSL (Domain Specific Language) provided by ScalaTest , via the FunSuite . 这是ScalaTest通过FunSuite提供的基本DSL(域特定语言)。

describe is a method, accepting a String and a by name value which returns Unit via a multiple argument list: describe是一个方法,接受一个String和一个名称值,它通过一个多参数列表返回Unit

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

It simply uses infix notation, that is why it looks semi "magical". 它只是使用中缀符号,这就是为什么它看起来半“神奇”。

it is a value which holds a class called ItWord . it是一个包含一个名为ItWord的类的值。 it has an apply method which simply registers the method you supply as a test: 它有一个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: _*)
  }
}

These are just methods and variables inherited from the mixin traits. 这些只是从mixin特征继承的方法和变量。 You can do a similar thing yourself: 你可以自己做类似的事情:

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

So if you mix it in another class, you can write 所以如果你把它混合在另一个类中,你可以写

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

(note that foo is a multi parameter list function, which does not exist in Java) (请注意, foo是一个多参数列表函数,在Java中不存在)

Because Scala lets you omit parentheses via infix notation , ( might be omitted and replaced with { to group the parameter-expression. So it becomes: 因为Scala允许您通过中缀表示法省略括号, (可能会省略并替换为{ to group the parameter-expression。所以它变为:

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

Now, all of these definitions are actually happening inside the primary constructor of MyClass1 现在,所有这些定义实际上都发生在MyClass1的主要构造函数中

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

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