开发者

Compile time type tracing

开发者 https://www.devze.com 2023-02-10 21:45 出处:网络
Is it possible to add some magic construct around a Scala expression so that it prints the type during com开发者_如何学Pythonpilation? E.g. have some class, magic function, meta programming type, whic

Is it possible to add some magic construct around a Scala expression so that it prints the type during com开发者_如何学Pythonpilation? E.g. have some class, magic function, meta programming type, which does:

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

// compile
// prints: Int


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.


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.


Something like this will work at runtime

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消