K.Alan K.Alan - 1 year ago 68
Scala Question

how to display value of case class in scala

case class Keyword(id: Int = 0, words: String)

val my= Keyword(123, "hello")

val fields: Array[Field] = my.getClass.getDeclaredFields

for (i <- fields.indices) {

println(fields(i).getName +":"+ my.productElement(i))



title:keyword's title

it's ok.

def outputCaseClass[A](obj:A){

val fields: Array[Field] = obj.getClass.getDeclaredFields

for (i <- fields.indices) {

println(fields(i).getName +":"+ obj.productElement(i))



it's wrong

nob nob
Answer Source

productElement is a Method of the Product Base trait.

Try to use a method signature like this:

def outputCaseClass[A <: Product](obj:A){ .. }

However it still won't work for inner case classes (fields also reports the $outer-Field, which productElement won't return and so it crashes with IndexOutOfBoundsException).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download