I'm working on Scala 2.12.17.
Let's say I've a bunch of case classes :
case class TestOne(one: String)
case class TestTwo(one: String, two: String)
case class TestThree(one: String, two: String, three: String)
I also have these types :
trait Data{
val a: Int
}
case class DoubleInt(a: Int, b: Int) extends Data
case class SingleInt(a: Int) extends Data
And this function which converts Data objects to String :
def loadData(input: Data): String = {
input.a.toString
}
What I'm looking forward is to pass Data object(s) to my case classe's apply method, then the apply method would use loadData function in order to convert each passed Data object into a String to make an instance of my case class. E.g :
val dataOne: Data = SingleInt(1)
val dataTwo: Data = DoubleInt(1, 2)
val testOne = TestOne(dataOne)
val testTwo = TestTwo(dataOne, dataTwo)
val testThree = TestOne(dataOne, dataTwo, dataOne)
Basically, TestOne apply method would be :
def apply(one: Data): TestOne = {
new TestOne(loadData(one))
}
TestTwo apply method would be :
def apply(one: Data, two: Data): TestTwo= {
new TestTwo(loadData(one), loadData(two))
}
Is there any way to programatically generate those apply methods at compile time ?
I thought that macros or paradise annotations would be useful for this use case, but I'm too unexperienced with these topics to even know where to start :/
Should
be
val testThree = TestThree(dataOne, dataTwo, dataOne)?So you'd like to replace
with just
Mapping over a tuple or case class is a standard task for example for Shapeless
If you want to hide
loadat all you can define a generic methodIf you want
maketo fail at compile time if the number of arguments is incorrect then the definition is a little more complicatedOr you can define a def macro
But if you really want to generate
applymethods in companion objects you can define macro annotaion (settings: Auto-Generate Companion Object for Case Class in Scala)