Avenger
Avenger

Reputation: 877

Access all case class values without reflection

I have a case class and i have a scenario where i want to get all the field value of case class in string separated by - and if the value is not present for case class use empty string in that case.I am able to do it but using reflection, is there any other way of doing it without reflection?

case class Test(
               a: String,
               b: Int
               )


val test = Test( a = "aValue",
                 b = 1
               ) 

val result = test.getClass.getDeclaredFields
                .map { field =>
                  field.setAccessible(true)
                  Option(field.get(test)).getOrElse("")
                }
                .mkString("-")

aValue-1 would should be the result

Upvotes: 1

Views: 292

Answers (1)

You can use the productIterator method all case classes have, followed with a mkString.

test.productIterator.map(v => Option(v).fold(ifEmpty = "")(_.toString)).mkString("-")

(btw, this doesn't smell good, the possibility of a null on a case class is a bad practice, and this feels like a very rustic way to encode data).

Upvotes: 3

Related Questions