Last active
June 13, 2022 21:45
-
-
Save heathermiller/354befb88b097330d42d to your computer and use it in GitHub Desktop.
Getting constructor arguments out of a case class, printing the names of the args and their runtime values
This file contains hidden or 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
import scala.reflect.runtime.universe._ | |
class AbstractParams[T: TypeTag] { | |
def tag: TypeTag[T] = typeTag[T] | |
override def toString: String = { | |
// Find all case class fields in concrete class instance and print them as "[field name] [field value]" | |
val tag = this.tag | |
val tpe = tag.tpe | |
val allAccessors = tpe.declarations.collect { case meth: MethodSymbol if meth.isCaseAccessor => meth } | |
val m = runtimeMirror(getClass.getClassLoader) | |
val im = m.reflect(this) | |
val ctorArg2Strings = allAccessors map { sym => | |
val fldMirror = im.reflectField(sym) | |
val value = fldMirror.get | |
"[" + sym.name + ": " + value + "]" | |
} | |
ctorArg2Strings.mkString(" ") | |
} | |
} | |
case class MyParams(id: String, stuff: Int) extends AbstractParams[MyParams] | |
object Ex extends App { | |
val p = new MyParams("joe", 2) | |
println(s"$p") | |
// prints: | |
// [id: joe] [stuff: 2] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment