Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check how many object properties are defined

Tags:

scala

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]
)
like image 228
UnguruBulan Avatar asked Dec 23 '22 23:12

UnguruBulan


1 Answers

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
like image 57
Krzysztof Atłasik Avatar answered Jan 07 '23 22:01

Krzysztof Atłasik