invariant
invariant

Reputation: 8900

How can I convert a case class to a Map (in Scala.js)

How can I convert a case class to a Map where the fields of the case class become the keys?

For example:

case class Person(name: String, age: Int)

val p = Person("dude", 89)
val map = p.toMap // <-- ???

so that map equals the following map:

Map("name" -> "dude", "age" -> 89)

Upvotes: 2

Views: 822

Answers (1)

sjrd
sjrd

Reputation: 22085

This is typically achieved with reflection or macros, since it involves looking up the names of Scala fields, which does not exist at runtime. In Scala.js, you're restricted to macros, since runtime reflection does not exist.

There are serialization libraries that do this transformation automatically with macros. Here are a couple candidates, which work in Scala.js:

Upvotes: 5

Related Questions