I am currently using the PPrint library to generate case classes to paste into my regression test Scala code, based on the values my existing code returns:
case class MyCaseClass(
byte: Option[Byte],
int: Option[Int],
long: Option[Long],
short: Option[Short],
double: Option[Double],
float: Option[Float],
boolean: Option[Boolean],
string: Option[String],
char: Option[Char]
)
val myValue = MyCaseClass(
byte = Some(1),
int = Some(1),
long = Some(1),
short = Some(1),
double = Some(1.0),
float = Some(1.0F),
boolean = Some(true),
string = Some("1"),
char = Some('1')
)
pprint.PPrinter.BlackWhite.pprintln(myValue)
This returns valid generated code that I can use:
MyCaseClass(
byte = Some(value = 1),
int = Some(value = 1),
long = Some(value = 1L),
short = Some(value = 1),
double = Some(value = 1.0),
float = Some(value = 1.0F),
boolean = Some(value = true),
string = Some(value = "1"),
char = Some(value = '1')
)
However, this is slightly more verbose than I want. Namely, I would pretty much never expliclty write a Some with an explicit value parameter (e.g. I would write Some(1) and not Some(value = 1)).
PPrint provides the defaultShowFieldNames property to disable parameter names, but this also disables the parameter names in my other case classes, which I do want generated.
pprint.PPrinter.BlackWhite.copy(defaultShowFieldNames = false).pprintln(myValue)
=>
MyCaseClass(
Some(1),
Some(1),
Some(1L),
Some(1),
Some(1.0),
Some(1.0F),
Some(true),
Some("1"),
Some('1')
)
I know I can specify additional handlers to PPrint to specially handle Some values, but as far as I can tell, I need to handle each possible case separately in order to guarantee valid code regardless of the generic type of the Some:
pprint.PPrinter.BlackWhite
.copy(additionalHandlers = {
case Some(value: Byte) => pprint.Tree.Literal(s"Some($value)")
case Some(value: Int) => pprint.Tree.Literal(s"Some($value)")
case Some(value: Long) => pprint.Tree.Literal(s"Some($value)")
case Some(value: Short) => pprint.Tree.Literal(s"Some($value)")
case Some(value: Double) => pprint.Tree.Literal(s"Some($value)")
case Some(value: Float) => pprint.Tree.Literal(s"Some(${value}F)")
case Some(value: Boolean) => pprint.Tree.Literal(s"Some($value)")
case Some(value: String) => pprint.Tree.Literal(s"Some(\"$value\")")
case Some(value: Char) => pprint.Tree.Literal(s"Some('$value')")
})
.pprintln(myValue)
=>
MyCaseClass(
byte = Some(1),
int = Some(1),
long = Some(1),
short = Some(1),
double = Some(1.0),
float = Some(1.0F),
boolean = Some(true),
string = Some("1"),
char = Some('1')
)
This approach doesn't handle all possible input values. For instance, if a value was another case class, it would fall back to the default Some(value = ...) handling.
How can I get PPrint to generate values in my desired format (parameter names for case classes other than Some, and no parameter names for Some values)?