I want to group elements of different types into one.
Following is one example
trait Element
case class ElementString(key:String,value:String) extends Element
case class ElementDouble(key:String,value:Double) extends Element
case class ElementInt(key:String,value:Int) extends Element
Grp(ElementString("2","abc"),ElementDouble("3",100.20),ElementInt("4",10))
One possible way is to use varargs
case class Grp(group:Element*)
.Is there any other efficient way to achieve the above . Any possible way to add elements one by one into Grp
Updated
I would also like to create a Group inside a Group.
A DSL like this is very common in scala because it is type-safe, but also very concise to use:
Alternative, no varargs:
You can use a quasi builder pattern by adding the a function:
Assuming group is a list. Note that this does make a new copy of the case class each time you call
withElement
. The code would then look like:You could create a real builder pattern if performance was important.