In ES6 we can refer to a field of an object as:
seller['firstname']
to represent
seller.firstname
Is there a way to do the same in Scala? I mean, to use strings to refer to object fields?
With Scala 2.13
, you should be able to do something more or less related by using case classes' new productElementNames
method which returns an iterator over its field names.
By zipping field names with field values obtained with productIterator
we can access a case class field value by using the string version of the field name:
implicit class CaseClassExtensions(obj: Product) {
def select[T](field: String): Option[T] =
(obj.productElementNames zip obj.productIterator)
.collectFirst { case (`field`, value) => value.asInstanceOf[T] }
}
// case class Seller(firstName: String, lastName: String)
Seller("Hello", "World").select[String]("firstName")
// Option[String] = Some(Hello)
Here, the implicit class is used to enrich the Product
type (which is case class inherited type) in order to call this select
method on any case class.
But contrary to what you're used to in Javascript:
Option
of the value (or you'd have to deal with exceptions when trying to get the value of a field which isn't defined).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With