mardi 18 août 2015

Scala: How to check if at least one of the fields of a class is defined?

I have a class which has several optional fields as given below:

class Container(f1: Option[String] = None,
                f2: Option[Boolean] = None,
                f3: Option[Int] = None,
                f4: Option[String] = None
                // ... 30 other fields which is unfortunate/terrible and
                // cannot be changed at the moment
                 ) {
  def hasAtleastOneDefinedField: Boolean = {
    this.f1.isDefined ||
      this.f2.isDefined ||
      this.f3.isDefined ||
      this.f4.isDefined
    // this is too-much of boilerplate
  }

  // This is something along the lines of what I want
  def hasAtleastOneDefinedField2: Boolean = {
    // this.getAllDeclaredFields.find(field => field.value.isDefined)
    ???
  }
}

Is it possible to do the same without using reflection ?





Aucun commentaire:

Enregistrer un commentaire