Justin
Justin

Reputation: 1

Getting case class field value with a val

I would like to be able to define a function that takes a case class field name as a parameter and uses the value of that field. Consider the code below:

case class Clock(hour: Int, minute: Int)

val clock = Clock(3, 55)
val field = "hour"
val hour = clock.field             //doesn't work

Is there a way in scala to achieve what this code tries to do? I haven't been able to find this question on S/O so I'm guessing this might not be something I should be trying to do. If that's true, why is that the case?

Upvotes: 0

Views: 126

Answers (2)

codejitsu
codejitsu

Reputation: 3182

You can try to use Dynamic here. Consider the example below:

class Clock extends Dynamic {
  def selectDynamic(field: String) = field
}

scala> val clock = new Clock
clock: Clock = Clock@6040af64

scala> clock.foo
res37: String = foo

scala> clock.selectDynamic("foo")
res38: String = foo

So, you can for example use pattern matching in selectDynamic to select the field.

Upvotes: 0

placeybordeaux
placeybordeaux

Reputation: 2216

With some basic text editing/macros you could just introduce a function such as

def clock_field(clock: Clock, field: String): Any = {
  field match {
    case "hour" => clock.hour
    case "minute" => clock.minute
  }
}

My scala isn't strong enough to make that pretty, but any text editor that allows for macros should make generating those easy.

Upvotes: 1

Related Questions