tzortzik
tzortzik

Reputation: 5133

could not find implicit value for parameter messages: play.api.i18n.Messages

I have the following piece of code

import play.api.i18n.{MessagesApi, Messages, I18nSupport}
import play.api.libs.json.Json

case class HttpMessage(key: String, message: String)

object HttpMessage {
  implicit val jsonFormat = Json.format[HttpMessage]

  def apply(key: String): HttpMessage = {
    HttpMessage(key, Messages(key))
  }
}

When compiled, it throws

[error] could not find implicit value for parameter messages: play.api.i18n.Messages
[error]     HttpMessage(key, messages(key))
[error]                              ^

I made some research and it seems that it cannot find an implicit value for MessagesAPI. It seems it must be inject like in controllers but I do not know how because I am facing an object and case class here. @Inject annotation is not accepted.

How can I fix this?

Upvotes: 1

Views: 1191

Answers (1)

insan-e
insan-e

Reputation: 3922

Approach from https://stackoverflow.com/a/30843682/4496364 :

import play.api.Play.current import play.api.i18n.Messages.Implicits._

The first line is deprecated since Play now uses DI everywhere possible.

My approach (can't say if good or bad):

case class HttpMessage(key: String, message: String)

object HttpMessage {
  implicit val jsonFormat = Json.format[HttpMessage]

  def apply(key: String)(implicit messages: Messages): HttpMessage = {
    HttpMessage(key, Messages(key))
  }
}

I had to create similar solution, so I used the implicit way, which Play uses also in it's templates. You must have implicit request in your controller for this to work. Also, in all service-like classes you need to forward this implicit messages: Messages...

Upvotes: 5

Related Questions