假设我正在构建一个库,并且我想向用户提供某些自定义编译时错误消息.有没有办法在Scala中提供这个,也许使用注释?
@annotation.implicitNotFound(msg = "Custom message.")如果未找到隐式参数,您可以使用提供自定义错误消息.请参阅此答案作为使用示例.
您还可以使用方法从宏实现中提供自定义编译错误消息Context#abort.
scala> f"%s"
<console>:8: error: percent signs not directly following splicees must be escaped
f"%s"
^
Run Code Online (Sandbox Code Playgroud)
此消息由功能提供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.")
}
Run Code Online (Sandbox Code Playgroud)
错误:
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)
^
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
616 次 |
| 最近记录: |