kornfridge kornfridge - 4 months ago 61
Scala Question

Scala - how to print case classes like (pretty printed) tree

I'm making a parser with Scala Combinators. It is awesome. What I end up with is a long list of entagled case classes, like:

ClassDecl(Complex,List(VarDecl(Real,float), VarDecl(Imag,float)))
, just 100x longer. I was wondering if there is a good way to print case classes like these in a tree-like fashion so that it's easier to read..? (or some other form of Pretty Print)

ClassDecl
name = Complex
fields =
- VarDecl
name = Real
type = float
- VarDecl
name = Imag
type = float


^ I want to end up with something like this

edit: Bonus question

Is there also a way to show the name of the parameter..? Like:
ClassDecl(name=Complex, fields=List( ... )
?

Answer

Check out a small extensions library named sext. It exports these two functions exactly for purposes like that.

Here's how it can be used for your example:

object Demo extends App {

  import sext._

  case class ClassDecl( kind : Kind, list : List[ VarDecl ] )
  sealed trait Kind
  case object Complex extends Kind
  case class VarDecl( a : Int, b : String )


  val data = ClassDecl(Complex,List(VarDecl(1, "abcd"), VarDecl(2, "efgh")))
  println("treeString output:\n")
  println(data.treeString)
  println()
  println("valueTreeString output:\n")
  println(data.valueTreeString)

}

Following is the output of this program:

treeString output:

ClassDecl:
- Complex
- List:
| - VarDecl:
| | - 1
| | - abcd
| - VarDecl:
| | - 2
| | - efgh

valueTreeString output:

- kind:
- list:
| - - a:
| | | 1
| | - b:
| | | abcd
| - - a:
| | | 2
| | - b:
| | | efgh
Comments