Say I am building a library and I want to provide certain custom compile time error messages to users. Is there a way to provide this in Scala, perhaps using annotations?
Asked
Active
Viewed 829 times
1 Answers
6
@implicitNotFound
You could use @annotation.implicitNotFound(msg = "Custom message.")
to provide your custom error message in case if implicit parameter is not found. See this answer as example of usage.
Macros
You could also provide custom compilation error messages from macro implementation using method Context#abort
.
scala> f"%s"
<console>:8: error: percent signs not directly following splicees must be escaped
f"%s"
^
This messages is provided by function macro_StringInterpolation_f
.
Example:
import scala.language.experimental.macros
import reflect.macros.Context
def half(ie: Int): Int = macro halfImpl
def halfImpl(c: Context)(ie: c.Expr[Int]): c.Expr[Int] = {
import c.universe.{ Constant, Apply, Literal }
val i = ie.tree match {
case Literal(Constant(i: Int)) => i
case _ => c.abort(c.enclosingPosition, "call this method with literal argument only.")
}
if (i % 2 == 0) c.literal(i / 2)
else c.abort(ie.tree.pos, "can't get half of odd number.")
}
Errors:
scala> half(2)
res0: Int = 1
scala> half(3)
<console>:1: error: can't get half of odd number.
half(3)
^
scala> val i = 0
i: Int = 0
scala> half(i)
<console>:2: error: call this method with literal argument only.
half(i)
^