Dot operator with string instead of member in Scala

548 Views Asked by At

I have a case class as:

case class abc (startDate:DateTime, endDate:DateTime)

In a different object that can access this case class, instead of accessing abc.startDate or abc.endDate, I would like to have a string that tells me whether it is start or end Date. So,

val decideStartOrEnd:String = "startDate"

Now I would like to get abc.startDate using this string variable decideStartOrEnd.

Any help is appreciated. Thanks in advance.

1

There are 1 best solutions below

1
Kamil Banaszczyk On

You can use use pattern matching in scala to obtain concrete object depends of string.

case class abc (startDate:LocalDate, endDate:LocalDate){

  def getTime(typeTime: String) : LocalDate = typeTime match {
    case "startDate" => startDate
    case "endDate" => endDate
    case _ => throw new IllegalArgumentException("Illegal argument")
  }

}

and use it like this for example

val decideStartOrEnd = "startDate"

val abe = abc(LocalDate.now(), LocalDate.now())

abe.getTime(decideStartOrEnd);

of course you can just type:

abe getTime "startDate"