Debilski
Debilski

Reputation: 67888

Compile time type tracing

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

Upvotes: 4

Views: 440

Answers (4)

jsalvata
jsalvata

Reputation: 2205

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.

Upvotes: 4

naedyr
naedyr

Reputation: 21

Something like this will work at runtime

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

Upvotes: 1

James Iry
James Iry

Reputation: 19367

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.

Upvotes: 9

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297275

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

Upvotes: 0

Related Questions