I'm quite new in Scala world.
Is there a better way to check how many properties are defined in an object, rather than going through all of them with idDefined()
and incrementing a value?
case class Obj (
a: Option[String],
b: Option[String],
c: Option[String],
d: Option[String]
)
Case classes extend Product
which provides productIterator
. You could use it like:
val obj = Obj(Some("a") ,Some("4"), None, None)
obj.productIterator.count {
case _: Some[_] => true
case _ => false
} // returns 2
or
obj.productIterator.count {
case x: Option[_] => x.isDefined
case _ => false
} // returns 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With