【问题标题】:Is there a way to provide custom compile error messages in Scala?有没有办法在 Scala 中提供自定义编译错误消息?
【发布时间】:2013-12-20 23:33:45
【问题描述】:

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

【问题讨论】:

    标签: scala annotations


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2011-05-04
      • 1970-01-01
      • 2023-03-05
      相关资源
      最近更新 更多