Scala macro to print code?

后端 未结 3 1666
面向向阳花
面向向阳花 2020-12-18 04:23

I want to do something like this:

def assuming[A](condition: => Boolean)(f: => A): A = {
  require(condition, /* print source-code of condition */)
  f         


        
3条回答
  •  佛祖请我去吃肉
    2020-12-18 04:53

    If you are using Scala 2.11.x the best way to go is the showCode method. This method will correctly print an arbitrary Scala tree. For example:

    scala> import reflect.runtime.universe._
    import reflect.runtime.universe._
    
    showCode(q"3.14 < 42")
    res1: String = 3.14.<(42)
    

    In the previous versions of Scala you would have to use the method show which does not guarantee correctness:

    scala> show(q"3.14 < 42")
    res2: String = 3.14.$less(42)
    

    The method showCode was designed with correctness in mind so it will not necessarily print beautiful code. If beauty is of importance for you can either contribute to the Scala Printers or you can write your own printer. Another interesting printer for Scala trees is the PrettyPrinter from Scala Refactoring.

提交回复
热议问题