Is there any way to write something like a \"unit test\" which makes sure some code does not compile?
Why would I want such a thing? Two reasons.
1
Scalatest can also do this.
Checking that a snippet of code does not compile
Often when creating libraries you may wish to ensure that certain arrangements of code that represent potential “user errors” do not compile, so that your library is more error resistant. ScalaTest Matchers trait includes the following syntax for that purpose:
"val a: String = 1" shouldNot compile
If you want to ensure that a snippet of code does not compile because of a type error (as opposed to a syntax error), use:
"val a: String = 1" shouldNot typeCheck
Note that the
shouldNot typeCheck
syntax will only succeed if the given snippet of code does not compile because of a type error. A syntax error will still result on a thrownTestFailedException
.If you want to state that a snippet of code does compile, you can make that more obvious with:
"val a: Int = 1" should compile
Although the previous three constructs are implemented with macros that determine at compile time whether the snippet of code represented by the string does or does not compile, errors are reported as test failures at runtime.