Compile-time type tracing

Is it possible to add some magic construct around the Scala expression so that it prints the type at compile time? For instance. have a certain class, a magic function, a type of metaprogram that does:

val i = 1 Some(11).map(Trace(_ + 1)) // compile // prints: Int 
+4
source share
4 answers

Not really, but how to do it

 $ 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) also works with a scalar.

+9
source

If things get really annoying, you can use this:

 scala -Xprint:typer -Xprint-types 

It gets hard to read, but tells you what the compiler thinks.

+4
source

Something like this will work at runtime

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

No, there is no such thing. A compiler plugin could do this.

0
source

Source: https://habr.com/ru/post/1339646/


All Articles