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

前端 未结 10 1845
情歌与酒
情歌与酒 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 23:06

    If you use Apache Spark, you can use the following method to print your case classes :

    def prettyPrint[T <: Product : scala.reflect.runtime.universe.TypeTag](c:T) = {
      import play.api.libs.json.Json
      println(Json.prettyPrint(Json.parse(Seq(c).toDS().toJSON.head)))
    }
    

    This gives a nicely formatted JSON representation of your case class instance. Make sure sparkSession.implicits._ is imported

    example:

    case class Adress(country:String,city:String,zip:Int,street:String) 
    case class Person(name:String,age:Int,adress:Adress) 
    val person = Person("Peter",36,Adress("Switzerland","Zürich",9876,"Bahnhofstrasse 69"))
    
    prettyPrint(person)
    

    gives :

    {
      "name" : "Peter",
      "age" : 36,
      "adress" : {
        "country" : "Switzerland",
        "city" : "Zürich",
        "zip" : 9876,
        "street" : "Bahnhofstrasse 69"
      }
    }
    

提交回复
热议问题