Let\'s say that I have a lot of similar data classes. Here\'s an example class User
which is defined as follows:
case class User (name: String,
Starting Scala 2.13
, case class
es (which are an implementation of Product) are now provided with a productElementNames method which returns an iterator over their field's names.
By zipping field names with field values obtained with productIterator one can obtained a Map
out of whatever case class:
// val user = User("Foo", 25, List("Lorem", "Ipsum"))
(user.productElementNames zip user.productIterator).toMap
// Map[String, Any] = Map("name" -> "Foo", "age" -> 25, "posts" -> List("Lorem", "Ipsum"))