UnguruBulan
UnguruBulan

Reputation: 1030

Check how many object properties are defined

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]
)

Upvotes: 4

Views: 196

Answers (1)

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22635

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

Upvotes: 10

Related Questions