简体   繁体   中英

Check case class with Option fields to make sure all of them are None using Shapeless HList

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?

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


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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM