Reputation: 462
I have a case class (simplified):
case class UserData(name: Option[String], age: Option[String]) {
lazy val nonEmpty = name.isDefined || age.isDefined // TODO
}
Can I replace the current implementation of nonEmpty
check using, for instance, Shapeless' HList in order to enumerate all the fields to check that all of them are set to None
or at least one has a value?
Upvotes: 3
Views: 1063
Reputation: 14825
I think you also check with pure scala using productIterator
.
scala> val data = UserData(None, None)
data: UserData = UserData(None,None)
scala> data.productIterator.forall {
| case x: Option[_] => x.isDefined
| case _ => false
| }
res2: Boolean = false
scala> val data = UserData(Some("foo"), Some("bar"))
data: UserData = UserData(Some(foo),Some(bar))
scala> data.productIterator.forall {
| case x: Option[_] => x.isDefined
| case _ => false // you may throw exception if you are not expecting this case
| }
res3: Boolean = true
Upvotes: 2
Reputation: 1095
case class UserData(name: Option[String], age: Option[String]) {
lazy val isEmpty = this.productIterator.forall(_ == None)
}
UserData(None,None).isEmpty
UserData(None,Some("s")).isEmpty
I suppose you want to do different behavior inside case class, if you dont then @pamu answer is what you are looking for. If you really want to use shapeless you can, but no need.
Upvotes: 2