Search code examples
scalacode-generationpojo

Scala CRUD pojo generation


I am trying to think of a way to implement a simple CRUD API in Scala with POST and PATCH methods for a type Foo. So, I have definitions for for my API of actual type Foo, a POST pojo and a PATCH pojo as follows:


case class Foo(
  id: String,
  field1: String,
  field2: Int
)

case class CreateFoo(
  field1: String,
  field2: Int
)

case class UpdateFoo(
  field1: Option[String],
  field2: Option[Int],
)

I'd like to avoid all this boiler plate and keeping all 3 classes in sync, ie if I wanted to add field3: Boolean. I started reading up on type macros and it seems to be the right tool for the job to generate all my pojos. However, I feel like this problem must be already solved and Im reinventing the wheel. Is there an already made solution?


Solution

  • It seems that you need code generation, so why don’t use a code generator (like Telosys for example https://www.telosys.org/ )

    With such a tool you define your class only once (in an “entity” file) and it generates all the repetitive code (wathever the language, in your case Scala)