Scala Macros: Making a Map out of fields of a class in Scala

后端 未结 3 707
孤独总比滥情好
孤独总比滥情好 2020-11-29 19:42

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,          


        
3条回答
  •  温柔的废话
    2020-11-29 20:10

    Starting Scala 2.13, case classes (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"))
    

提交回复
热议问题