Scalaxy/Debug: macros that make Predef.assert, require and assume a joy to use!
Quick link: jump to Scalaxy/Debug straight away!
Throughout languages, assertions have proved to be a handy tool for programmers who want “light” error checks for very unlikely error cases (these checks are typically only performed in Debug builds so as not to slow down Release code).
In C / C++, assert macros usually print out the exact source code of the expression that failed the assertion check, which is often more than enough to understand the meaning of the failure.
In Java and Scala though, you have to provide your own message if you don’t want to be presented with an anonymous failure trace:
-
SomeAssert.java:
assert x.getSize() == 2 : "Size of x is not 2"; // Java assert
-
SomeAssert.scala:
assert(x.size == 2, "Size of x is not 2") // Scala assert
How often do you find yourself writing the following code?
assert(a == b, "a == b (" + a + " != " + b + ")")
Or, more recently (string interpolation FTW!):
assert(a == b, s"a == b ($a != $b)")
Well, thanks to Scalaxy/Debug macros, you can now forget about this kind of grungy code:
import scalaxy.debug._
val a = 10
val b = 12
assert(a == b)
// this will throw:
// "assertion failed: a == b (10 != 12)"
You just need to add the following to your build.sbt file to get going:
// Only works with 2.10.0+
scalaVersion := "2.10.0"
// Dependency at compilation-time only (not at runtime).
libraryDependencies += "com.nativelibs4java" %% "scalaxy-debug" % "0.3-SNAPSHOT" % "provided"
// Scalaxy/Debug snapshots are published on the Sonatype repository.
resolvers += Resolver.sonatypeRepo("snapshots")
Oh, and this works with assert, assume and require.
Enjoy! (please file any bug on Scalaxy/Debug’s GitHub and follow me on Twitter if you find this useful :-))