Skip to content

Instantly share code, notes, and snippets.

@taintech
Last active February 3, 2018 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taintech/7f2389ac34cb36fab0a470efe9b712be to your computer and use it in GitHub Desktop.
Save taintech/7f2389ac34cb36fab0a470efe9b712be to your computer and use it in GitHub Desktop.
Scala print case class members name and values
object helper {
def printCaseClass(caseClass: AnyRef): Unit = {
def caseClassToMap(caseClass: AnyRef): Map[String, Any] = {
(Map.empty[String, Any] /: caseClass.getClass.getDeclaredFields) {
(a, f) =>
f.setAccessible(true)
a + (f.getName -> f.get(caseClass))
}
}
println(caseClass.getClass.getSimpleName + "(")
println(
caseClassToMap(caseClass)
.map {
case (field, value) =>
s"$field = ${if (value.isInstanceOf[String]) s""""$value""""
else value.toString}"
}
.mkString(", \n"))
println(")")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment