Suppose I have the following code. Lets say alternative constructors are provided for syntactic sugar (assume this is a requirement):
object Example extends App {
case class Doggy(name: Option[String] = None, age: Option[Int] = None)
object Doggy {
def apply(name: String): Doggy = Doggy(name = Some(name))
def apply(age: Int): Doggy = Doggy(age = Some(age))
def apply(name: String, age: Int): Doggy = Doggy(name = Some(name), age = Some(age))
}
val rex = ("rex", 10)
val pex = ("pex")
val tex = (100)
}
As you can see, the alternate constructor provides syntactic sugar allowing the user to skip writing Some(name) or Some(age) and so on.
Now in the use cases for this case class, all possible combinations of the constructor may be utilised by the user.
For a case class with many different options, constructing alternate constructors by defining apply() quickly becomes unwieldy.
Is there a way to somehow generate all combinations of the apply() programmatically?
For example, here is a stack overflow question where lists are passed to the constructor:Link. Could we generate all combinations of a list, and define an apply() on each combination?
I realise this may not be possible, but any guidance would be appreciated (perhaps even ways to improve the code pattern provided)
Aucun commentaire:
Enregistrer un commentaire