Let's say that I have this class
case class Test (id: Long, name: String)
and an instance of this class :
Test :
id -> 1
name -> toto
I would like to create a Map[String, String] as follow :
Map( "id" -> "1", "name" -> "toto")
My question is : Is there a way to turn this instance of Test into Map[String, String] ? I want to avoid to use a method as this one :
def createMap(instance: Test): Map[String, String] = {
val map = new Map[String, String]
map.put("id", instance.id.toString)
map.put("name", instance.name)
map
}
If there is no method to do so in Scala, is there a way to iterate over class properties ? Maybe I can create a generic function to do so :
def createMap(instance: T): Map[String, String] = {
val map = new Map[String, String]
//pseudocode
for ((name, value) <- instance.getClassProperties.getValues) {
case value.isInstanceOf[String] : map.push(name, value)
case _ : map.push(name, value.toString)
}
map
}
Is that possible ? If you have good examples/links, I'm interested.
Map("id" -> t.id.toString, "name" -> t.name)
wheret
is an instance ofTest
.