I'm just starting out with scala here and I'm finding some of the syntax confusing. For example from the scalatest main page
class ExampleSpec extends FlatSpec with Matchers {
"A Stack" should "pop values in last-in-first-out order" in {...}
}
As I read it that means "should" is a method of string "A stack"? If that is right, how does that happen? It doesn't seem to work from the scala prompt
scala> class ExampleSpec {
| "A Stack" should "pop values"
| }
<console>:9: error: value should is not a member of String
"A Stack" should "pop values"
If "should" is not a method of string "A Stack" in the above snippet then how am I to read the snippet correctly? What is "should" and how does it relate to the string? Any clues?
This is commonly known as the
Pimp My LibraryEnrich My Library pattern where we can extend other libraries (in this case Scala strings) with our own methods by using implicit conversions.The way it works is that
FlatSpec
mixes in a trait calledShouldVerb
which has the following implicit conversion defined:And
StringShouldWrapperForVerb
has theshould
method defined:The reason it does not work in the REPL for you is that you don't have
FlatSpec
and via that theShouldVerb
trait mixed in.You can read more about this in the documentation under implicit classes.