有没有办法在Scala中提供自定义编译错误消息?

时间:2013-12-20 14:30:46

标签: scala annotations

假设我正在构建一个库,并且我想向用户提供某些自定义编译时错误消息。有没有办法在Scala中提供这个,也许使用注释?

1 个答案:

答案 0 :(得分:6)

@implicitNotFound

如果找不到隐式参数,您可以使用@annotation.implicitNotFound(msg = "Custom message.")提供自定义错误消息。请参阅this answer作为使用示例。

您还可以使用方法Context#abort从宏实现中提供自定义编译错误消息。

scala> f"%s"
<console>:8: error: percent signs not directly following splicees must be escaped
              f"%s"
                ^

此消息为provided,函数为macro_StringInterpolation_f

示例:

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.")
}

错误:

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)
                  ^