Compile time type tracing

╄→гoц情女王★ 提交于 2020-01-01 11:48:31

问题


Is it possible to add some magic construct around a Scala expression so that it prints the type during compilation? E.g. have some class, magic function, meta programming type, which does:

val i = 1
Some(11).map(Trace(_ + 1))

// compile
// prints: Int

回答1:


Not exactly, but how 'bout this

$ cat Test.scala
def Trace[T] = identity[T] _

val i = 1
Some(11) map {x => Trace(x + 1)}



$ scala -Xprint:typer Test.scala 2>&1 | egrep --o 'Trace\[.*\]'
Trace[T >: Nothing <: Any]
Trace[Int]

The first Trace comes from the definition of Trace and can be ignored. The same parameter (-Xprint:typer) works with scalac, too.




回答2:


If things get really nasty, you can use this:

scala -Xprint:typer -Xprint-types

Gets difficult to read, but tells you exactly what the compiler is thinking.




回答3:


Something like this will work at runtime

def Type[T](x:T):T = {println(x.asInstanceOf[AnyRef].getClass()); x }



回答4:


No, there's no such thing. A compiler plugin might be able to do it.



来源:https://stackoverflow.com/questions/4992456/compile-time-type-tracing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!