Mohan
Mohan

Reputation: 8863

'result should have length 3': How does the ScalaTest DSL work?

ScalaTest allows you to write code like:

result should have length 3

What's going on under the hood to make this parse? Is it just using the infix notation, i.e. is it

result.should(have).length(3)

through some magic involving implicits? Or is there something more complex going on?

Upvotes: 3

Views: 110

Answers (1)

Andrey Tyukin
Andrey Tyukin

Reputation: 44957

You are exactly right: it's magic with implicits + infix syntax.

Let's take your example apart. In

result should have length 3

the expression result (usually) does not have the method should. However, if you mixin Matchers, then you get the implicit conversion convertToAnyShouldWrapper, which returns an AnyShouldWrapper. This AnyShouldWrapper now has an overloaded method should.

One of the versions of should takes a HaveWord as argument, and returns a weird thing called ResultOfHaveWordForExtent. The ResultOfHaveWordForExtent now has a length method, which takes a Long, and finally returns an Assertion.

Thus, your statement is desugared into:

convertToAnyShouldMatcher(result).should(have).length(3)

Notice that the method calls and arguments alternate in this chain. So in case you are not sure whether it's something like should be or shouldBe, just count the expressions, and look whether the next argument you want to supply is in an odd or an even position.

Upvotes: 3

Related Questions