Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying object fields with strings in Scala

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?

like image 374
Jose Cabrera Zuniga Avatar asked Jan 27 '23 06:01

Jose Cabrera Zuniga


1 Answers

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:

  • This is limited to case classes.
  • This returns an 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).
  • You have to specify the return type of the associated value.
like image 59
Xavier Guihot Avatar answered Jan 28 '23 20:01

Xavier Guihot