CodexBloom - Programming Q&A Platform

How to implement guide with implicit conversions in scala 2.13.8 causing unexpected nullpointerexception

πŸ‘€ Views: 42 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
scala play-framework implicit-conversion Scala

I tried several approaches but none seem to work... I'm working with a `NullPointerException` that seems to arise from an implicit conversion I have in my Scala code. I'm using Scala version 2.13.8 and the Play Framework 2.8.8. The implicit conversion is meant to convert a `String` to a custom `User` type, but it appears that when I attempt to use it, I'm getting null values instead of the expected `User` instances. Here's the code snippet where I define my implicit conversion: ```scala case class User(name: String) object User { implicit def stringToUser(name: String): User = { if (name == null || name.isEmpty) throw new IllegalArgumentException("Name want to be null or empty") User(name) } } ``` And here’s how I’m trying to use the conversion in my controller: ```scala def greetUser(userName: String) = Action { implicit request => val user: User = userName // Implicit conversion triggered here Ok(s"Hello, ${user.name}") } ``` When I call `greetUser(null)` or `greetUser("")`, I expect to catch an `IllegalArgumentException` from the conversion, but instead, I get a `NullPointerException` when trying to access `user.name`. I've verified that my implicit conversion is in scope, and I'm logging the value of `userName` before the conversion call, which shows that it's indeed null or empty. I've tried wrapping the `userName` in an `Option` to handle this more gracefully, but I still need to figure out why the conversion isn't working as expected. Can anyone suggest what I might be missing or how to resolve this scenario? This is part of a larger service I'm building. Any help would be greatly appreciated! I'm using Scala LTS in this project. Any ideas how to fix this? Any ideas what could be causing this?