Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 434
Alexey Sirenko Avatar asked Dec 20 '25 03:12

Alexey Sirenko


1 Answers

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.

like image 143
Pedro Correia Luís Avatar answered Dec 21 '25 18:12

Pedro Correia Luís