0

I am new to Play and Scala as well. And I meet a problem with i18n while reading book "Play with Scala". The problem was the Messages object, which has to be obtained in every template to let application work properly.

What bothers me is that even if I don't use the Messages object in one of my Scala template files, but I inherit/call another template in it, I still have to add (implicit messages: Messages) at the top of the file.

Can somebody explain me why is that? Is it necessary to add the Messages object in every template? Its quite problematic and I am sure it can be solved somehow.

Peter Neyens
  • 9,770
  • 27
  • 33
azalut
  • 4,094
  • 7
  • 33
  • 46

1 Answers1

0

This is not a Play Framework specific problem, it is just how implicit parameters work in Scala (see Understanding implicit in Scala).

Take the following function which "magically" adds a number to a list of numbers.

def addMagic[A](numbers: List[Int])(implicit add: Int) = numbers.map(_ + add)

We can use addMagic as follows :

{
  implicit val magicNumber = 42
  addMagic(List(1, 2, 3))
  // List[Int] = List(43, 44, 45)
}

If we use addMagic in another function without passing an implicit Int :

def printMagicNumbers(numbers: List[Int]) = println(addMagic(numbers))

we get the following error:

error: could not find implicit value for parameter add: Int

So we also need to add an implicit parameter to printMagicNumbers :

def printMagicNumbers(numbers: List[Int])(implicit add: Int) = 
  println(addMagic(numbers))

In the same manner your template function needs an implicit Messages object if it calls a template function which needs the Messages object.

Community
  • 1
  • 1
Peter Neyens
  • 9,770
  • 27
  • 33