advanced patterns with Scala 3 implicits in a type-safe builder pattern
I'm having trouble with I just started working with I'm working on a personal project and I'm working on a personal project and I tried several approaches but none seem to work... I'm working with an scenario while trying to implement a type-safe builder pattern in Scala 3. I have a case class `Person` and a builder class `PersonBuilder` that uses implicits to help set the fields of `Person`. However, I'm running into a strange behavior where the compiler sometimes fails to resolve the implicit conversions correctly, leading to a `could not find implicit value for parameter` behavior when trying to compile my code. Here's a simplified version of what I have: ```scala case class Person(name: String, age: Int) class PersonBuilder { private var name: Option[String] = None private var age: Option[Int] = None def withName(n: String): this.type = { name = Some(n) this } def withAge(a: Int): this.type = { age = Some(a) this } def build()(implicit ev: PersonBuilder.CanBuild): Person = { Person(name.getOrElse("Unknown"), age.getOrElse(0)) } } object PersonBuilder { trait CanBuild implicit val canBuild: CanBuild = new CanBuild{} } ``` And here is how I'm trying to use `PersonBuilder`: ```scala val person = new PersonBuilder().withName("Alice").withAge(30).build() ``` However, if I try to separate the `withName` and `withAge` calls like this: ```scala val builder = new PersonBuilder() val person = builder.withName("Alice").build() ``` I see the behavior: `could not find implicit value for parameter ev: PersonBuilder.CanBuild`. It seems that the implicit `CanBuild` instance is not recognized when I call `build()` after setting only the name. I’ve tried explicitly passing the implicit parameter: ```scala val person = builder.withName("Alice").build()(PersonBuilder.canBuild) ``` But this feels cumbersome and does not align with the builder pattern I was aiming for. Additionally, this behavior is not consistent, as sometimes it works without needing to pass the implicit explicitly. Is there a better way to define my builder that maintains type safety while ensuring that implicits are resolved correctly? Am I missing something in my design? I'm using Scala 3.1.0. Any insights would be greatly appreciated! For context: I'm using Scala on Ubuntu. My development environment is macOS. How would you solve this? My team is using Scala for this service.