Is it possible to map the key value pairs of a Map to a Scala constructor with named parameters?
That is, given
class Person(val firstname: String, val lastname: String) {
...
}
… how can I create an instance of Person using a map like
val args = Map("firstname" -> "John", "lastname" -> "Doe", "ignored" -> "value")
What I am trying to achieve in the end is a nice way of mapping Node4J Node objects to Scala value objects.
The key insight here is that the constructor arguments names are available, as they are the names of the fields created by the constructor. So provided that the constructor does nothing with its arguments but assign them to fields, then we can ignore it and work with the fields directly.
We can use:
Which we can call on a blank person:
Of course we can do better with a little pimping:
so that you can call:
If having to call the constructor is annoying, Objenesis lets you ignore the lack of a no-arg constructor:
Now we can combine the two to write