0

I am working on a code where I need to access the fields of a case class based on field name in a method. Explaining in the below code

Case Class Department(
            projectId: String,
            name: Option[String],
            id1: Option[String],
            id2: Option[String],
            id3: Option[String],
            age: Option[Int]
){

def logicOnId(): Boolean = {
  ???
  }
}

I want to write the same logic on all the three ids. I can write it as follows:

def logicOnId1(): Boolean = {
  someLogic(this.id1)
  }

def logicOnId2(): Boolean = {
  someLogic(this.id2)
  }

def logicOnId3(): Boolean = {
  someLogic(this.id3)
  }

But this is not an ideal way since it is the same logic on different columns. So, I want the process/way to write a method so that it can be used on multiple fields like

def logicOnId(input: String): Boolean = {
  someLogic(input)
  }

where this input is id1 or id2 or id3 as a String.

7
  • You can use reflection (runtime would be fine in your case), but it's not something encouraged. Commented Apr 18, 2022 at 13:10
  • Can you please provide the steps or any article for achieving this using reflection ?? Commented Apr 18, 2022 at 13:13
  • Sure, here's the scaladoc about runtime reflection! Commented Apr 18, 2022 at 13:15
  • 2
    1. Runtime reflection is not recommended. 2. Having business logic on case class is not recommended. Commented Apr 18, 2022 at 15:01
  • @cchantep Completely right! Commented Apr 18, 2022 at 17:10

1 Answer 1

1

No need to go down the route of runtime reflection, just use good type modeling:

final case class Department(
    projectId: String,
    name: Option[String],
    id1: Option[String],
    id2: Option[String],
    id3: Option[String],
    age: Option[Int]
) {
  private def someLogic(input: Option[String]): Boolean =
    ???

  def logicOnId(id: ID): Boolean =
    id match {
      case ID.ID1 =>
        someLogic(this.id1)

      case ID.ID2 =>
        someLogic(this.id2)

      case ID.ID2 =>
        someLogic(this.id3)
    }
}

sealed trait ID
object ID {
  final case object ID1 extends ID
  final case object ID2 extends ID
  final case object ID3 extends ID
}
Sign up to request clarification or add additional context in comments.

1 Comment

I would use nameOf library to avoid the sealed trait in this case. Not sure it works inside the case class itself though.

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.