K.Alan K.Alan - 1 month ago 9
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))

}


id:123

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))

}
}

outputCaseClass(my)


it's wrong

nob nob
Answer

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).

Comments