Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save adarshaj/18c631e9853fc77084b3d520c7ea4b76 to your computer and use it in GitHub Desktop.
Save adarshaj/18c631e9853fc77084b3d520c7ea4b76 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
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