Let’s say Product is in a Java library that I can’t tweak, so to instantiate it by calling setters:
val product = new Product
product.setName("Cute Umbrella")
product.setSku("SXO-2")
product.setQuantity(5)
I’d prefer to be able to do something like this:
val product = new Product {
_.setName("Cute Umbrella")
_.setSku("SXO-2")
_.setQuantity(5)
}
or better yet:
val product =
new Product(name -> "Cute Umbrella", sku -> "SXO-2", quantity -> 5)
Is something like this possible with Scala ?
I’d write an implicit conversion to use Apache Commons BeanUtils
You don’t get property name or type checking at compile time, but it is very close to the syntax that you wanted, and is generally very useful in creating eg testdata.
Or taking a cue from @retronym’s function approach