Michael Lafayette
Michael Lafayette

Reputation: 3072

How can we trace expressions / print statements with line numbers in Scala?

If you want print statements with line numbers, how do you do it?

Upvotes: 1

Views: 1023

Answers (2)

Michael Lafayette
Michael Lafayette

Reputation: 3072

It depends on what you want to do.

With the scala-trace-debug library, you can type something like this:

Debug.trace(1 + 2)

And get this:

"3" in thread main:
    path.to.file(file.Scala: 22) // click-able stack trace

You can customize the number of lines of stack trace, like so:

Debug.trace(1 + 2, 3) // 3 lines of stack trace

And if you do info.collaboration_station.debug._, you can even do this:

val three = 3.trace

...

"3" in thread main:
    path.to.file(file.Scala: 22)

Finally, there is support for expressions:

Debug.traceExpression{
    val myVal = 4
    1 + 2 + myVal
}

...

"{
  val myVal = 4;
  (3).+(myVal)
} -> 7" in thread main:
    at main.Main$.main(Main.scala:12)

Unlike the other library, this is more geared toward debugging. If I wanted to provide a history of what was going on and I did not want the user to see a stack trace, I would not use this tool.

Upvotes: 2

lutzh
lutzh

Reputation: 4965

Check out Haoyi Li's sourcecode library, I think it gives you what you are looking for.

sourcecode is a small Scala library for that provides common "source code" context to your program at runtime, similar to Python's __name__, C++'s __LINE__ or Ruby's __FILE__. For example, you can ask for the file-name and line number of the current file, either through the () syntax or via an implicit.

See for example https://github.com/lihaoyi/sourcecode#logging

You can use sourcecode.File and sourcecode.Line to define log functions that automatically capture their line number and file-name

def log(foo: String)(implicit line: sourcecode.Line, file: sourcecode.File) = {
  println(s"${file.value}:${line.value} $foo")
}

log("Foooooo") // sourcecode/shared/src/test/scala/sourcecode/Tests.scala:86 Fooooo

Upvotes: 3

Related Questions