Search code examples
scaladebuggingstack-tracetrace

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?


Solution

  • 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.