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

前端 未结 10 1871
情歌与酒
情歌与酒 2020-12-07 22:35

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

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 22:50

    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
    

提交回复
热议问题