W scali, jak zamienić wartości obiektów na Mapę [String, String]?
Powiedzmy, że mam tę klasę
case class Test (id: Long, name: String)
i wystąpienie tej klasy:
Test :
id -> 1
name -> toto
Chciałbym utworzyć Mapę [String, String] w następujący sposób:
Map( "id" -> "1", "name" -> "toto")
Moje pytanie brzmi: czy istnieje sposób na przekształcenie tego wystąpienia Testu w Mapę [String, String]? Chcę uniknąć stosowania metody takiej jak ta:
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
}
Jeśli w Scali nie ma metody, aby to zrobić, czy istnieje sposób na iterację właściwości klasy? Może uda mi się stworzyć ogólną funkcję:
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
}
Czy to jest możliwe ? Jeśli masz dobre przykłady / linki, jestem zainteresowany.