1
votes

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?

1
You could mark your object @Singleton and inject it where you need.insan-e
Or try to import play.api.i18n.Messages.Implicits._insan-e
I already tried to import. Not working.tzortzik
@insan-e How can I inject in @Singleton ?tzortzik
You also need implicit application in scope for Messages implicits, so import play.api.Play.current import play.api.i18n.Messages.Implicits._, it should work, but Play.current approach is deprecated.insan-e

1 Answers

4
votes

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...