cerst / auto_require

Scala's require with automated, macro-based error messages

Version Matrix

GitHub license Maven Central

auto-require

auto_require is a macro implementation of Scala's require that comes with auto-generated error messages.
It has no dependencies other than scala-reflect.

Usage

libraryDependencies ++= Seq(
    "com.github.cerst" %% "auto-require" % autoRequireVersion
)
import com.github.cerst.autorequire._

final case class Person(age: Int, name: String) {
    autoRequire[Person](!(age < 13) && name.nonEmpty)
}

val _ = Person(10, "John")
// Exception in thread "main" [...]: Requirement failed for 'Person': '!(Person.this.age < 13) && scala.Predef.augmentString(Person.this.name).nonEmpty' { Person.this.age = 10, Person.this.name = John }

In order to display the error message above, the macro generates variable declarations for all variables found in the expression.
Whereas you can use autoRequire everywhere, you always need to specify a generic type as the latter is displayed in the error message.
If you prefer not throwing exceptions, you can use autoRequireEither.
There are a few ways to customize the error message. Please check the Scaladoc of com.github.cerst.autorequire.DisplayConfig and its sub-types for more info.