jeudi 30 août 2018

scala check if at least one case class field value is nonEmpty using reflection

I have a requirement that for a given case class with around 30+ Option[T] fields needs to have at least 1 field nonEmpty in order to be valid. Instead of checking each field individually I opted for checking all fields via reflection in a generic way. The code I came up with (based on some other answers in SO as well) was:

import scala.reflect.runtime.universe._
import scala.reflect.runtime.{universe => ru}

  // gets all methods of a Case Class
  def getMethods[T: ru.TypeTag] = typeOf[T].members.collect {
    case m: MethodSymbol if m.isCaseAccessor => m
  }.toList


  /**
    *  Returns the value of all Case Class fields
    * @param obj case class object
    * @return a Sequence of all field values
    */
  def getAllCaseClassFieldValues[T: ru.TypeTag](obj: Object): Seq[Any] = {
    val mirror = ru.runtimeMirror(getClass.getClassLoader)
    getMethods[T].map(m => mirror.reflect(obj).reflectField(m).get)
  }

The case class:

case class SampleRequest(field1: Option[String], field2: Option[String], //.... up to 30 or more fields

The code that checks to see if at least 1 is nonEmpty:

 val fieldValues = getAllCaseClassFieldValues[SampleRequest](r)
 val noneCount = fieldValues.count(_ == None)
 val atLeastOneNonEmpty = noneCount < fieldValues.size

I was wondering if there would be a better way for validating this via reflection or other mechanism?





Aucun commentaire:

Enregistrer un commentaire