CodexBloom - Programming Q&A Platform

Unexpected NPE when using implicits in Scala 3.1.0 with case class parameters

👀 Views: 381 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-23
scala scala-3 implicits Scala

I'm stuck trying to I've been working on this all day and I tried several approaches but none seem to work. I'm working with a NullPointerException when trying to instantiate a case class using an implicit parameter in Scala 3.1.0. The case class is defined to take an implicit value but fails to resolve it properly, leading to runtime exceptions. Here's a simplified example of my code: ```scala case class Config(value: String) object Config { implicit val defaultConfig: Config = Config("default") } case class Service(implicit config: Config) { def showConfig(): String = config.value } object Main extends App { // Uncommenting the next line gives NPE // val service = Service() // behavior: NullPointerException occurs here val serviceWithDefault = new Service()(Config.defaultConfig) println(serviceWithDefault.showConfig()) } ``` When I try to instantiate `Service` without passing the implicit `Config`, I expect it to fall back to the default implicit value, but instead, I get the following behavior: ``` Exception in thread "main" java.lang.NullPointerException at Service.showConfig(Service.scala:5) ``` I've verified that `Config.defaultConfig` is properly defined, and I've checked that the implicit scope includes it. However, it seems like the implicit parameter is not being resolved as I expected. I've also tried different ways of defining the implicit, like using a companion object or passing it explicitly, but nothing seems to work. Is there a known scenario with implicits in Scala 3.1.0 that could lead to this behavior? How can I resolve this NPE when using implicits with case classes? I'm working on a web app that needs to handle this. Could this be a known issue? I recently upgraded to Scala 3.10.