I want to create a case class which can incorporate a record of string and another case class entity.
For example:
case class Student(
name: String
age: Int
)
case class Example(
[key:String]: Student
)
Now I want to use Example
to add multiple attributes where attribute
could have N number of elements however the type of all those attributes would remain Student. Here's an example:
Example(student1 = Student("name",12),student2=Student("name2",13))
Reason why I am using Case class is that I need to transform this into a JSON using UPickle library and so I wanted to know on the feasibility of achieving the same.
Please note that Example
class not just contains [key:String]: Student
attribute types but also somethings like:
case class Example(
[key:String]: Student,
_logOp: Option[Boolean] = false,
queryName: String,
...
)
The transformed result for case class:
case class Example(
_logOp: String,
variation: String,
[key:String]: FiltersCaseClass
/* This line I have added to simplify and make my problem more understandable. Basically the case class would contain some properties like `_logOp` `variation` and then a lot of keys with their values as another case class `FilterCaseClass`
*/
)
should look something like this:
{"_logOp":"AND","variation": "en","ids": {"_logOp": "OR","_expressions": [{"value": "242424"},{"value": "242422"}]}}
where FilterCaseClass is:
case class FilterCaseClass(
_logOp: String,
_expressions: Seq[SingleValueFilter]
)
where SingleValueFilter is another case class containing values
Edit 1:
As per one of the answers by Dymtro:
case class Example(
m: Map[String, Student],
_logOp: Option[Boolean] = Some(false),
queryName: String
)
object Example {
implicit val rw: ReadWriter[Example] = macroRW
}
write(Example(
Map("student1" -> Student("name",12), "student2" -> Student("name2",13)),
Some(true),
"abc"
))
//{"m":{"student1":{"name":"name","age":12},"student2":{"name":"name2","age":13}},"_logOp":[true],"queryName":"abc"}
The only difference I want here is:
{"student1":{"name":"name","age":12},"student2":{"name":"name2","age":13},"_logOp":[true],"queryName":"abc"}
The difference is that I want case class to be flexible to add key value pairs of Student class.
You don't need a case class
Example
, in µPickle you can create a json mixing manual construction and case-class constructionIf
[key:String]: Student
meansMap[String, Student]
then µPickle seems to support this out-of-the-boxYou can achieve this with a custom codec (pickler)
So, basically you can generate case classes in Scala but it's not necessary for serialization into json format.
Just for the completeness, since your original question was how to define a case class, here is a code with actual case-class definition. But this code is slow (since it uses runtime reflection and runtime compilation) and is not conventional Scala code (on contrary to the above custom picklers)
q"..."
is a string interpolator for quasiquotes (creating abstract syntax trees).