Last active
February 3, 2018 20:27
-
-
Save taintech/7f2389ac34cb36fab0a470efe9b712be to your computer and use it in GitHub Desktop.
Scala print case class members name and values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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