1
case class Foo {
    fieldA: Option[Double],
    fieldB: Option[Double]
}

    val foo = Foo( 
        fieldA = Some(1.0), 
        fieldB = Some(2.0)
)

Given the string "fieldA", I want to get the value of foo.fieldA, which is Some(1.0). Is it possible to NOT use reflection, since the code is going to be used in production?

4
  • Not sure what you mean by "NOT use reflection". You can use foo.fieldA.get which returns 1.0. Commented Apr 23, 2018 at 17:36
  • In your example code, fieldA is Some(1.0) not Some(2.0). Commented Apr 23, 2018 at 17:48
  • @jwvh thanks. updated. Commented Apr 23, 2018 at 18:36
  • @Brian When provided with "fieldA", I don't really know it's foo.fieldA that I need. So the question is how to get foo.fieldA from the string. Commented Apr 23, 2018 at 18:38

1 Answer 1

3

I guess the short answer is "no".

A slightly longer answer is that, if you want to retrieve a field from any element, using just a string with the name of that element, then you have to use reflection.

That said, you could write a look-up function, as follows:

case class Foo(fieldA: Option[Double], fieldB: Option[Double]) {

  //...

  def byFieldName(name: String): Option[Double] = name match {
    case "fieldA" => fieldA
    case "fieldB" => fieldB
  }
}

It's a bit manual, but it works. Alternatively, you could implement this function using reflection, caching the result in a Map[String, Option[Double]] (assuming all such fields have the same type). That way, you would only get the performance hit once for each looked-up field.

UPDATE: I should point out that maybe this isn't what you want in any case. If you need to retrieve field values by name, would the following work for you instead of a case class (demonstrated in the Scala REPL)?

scala> type Foo = Map[String, Option[Double]]
defined type alias Foo

scala> val foo: Foo = Map("fieldA" -> Some(1.0), "fieldB" -> Some(2.0))
foo: Foo = Map(fieldA -> Some(1.0), fieldB -> Some(2.0))

scala> foo("fieldA")
res0: Option[Double] = Some(1.0)

That is, could you use a Map data structure to lookup labeled values?

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the inspiration. I was thinking about converting the case class to Map, but I guess the "manual solution" would work best. Thank you!!!! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.