shomik naik
shomik naik

Reputation: 255

How does this Play 2 ScalaTemplates code work

Please explain the code below:

@title(text: String) = @{
  text.split(' ').map(_.capitalize).mkString(" ")
}

<h1>@title("hello world")</h1>

Upvotes: 2

Views: 219

Answers (1)

mguymon
mguymon

Reputation: 9015

A breakdown of the reusable code block @title(text: String)

  1. text.split( ' ' ) separates the text into a List by splitting the string by ' ', e.g. "hello world" would become ["hello", "world"]

  2. map(_.capitalize) iterates the List, calls capitalize on each element, and returns the new List, e.g. ["hello", "world"] becomes ["Hello", "World"]. This blog post give a good overview of _.

  3. mkString(" ") converts the List back to a String by joining the string with " ", e.g. ["Hello", "World"] becomes "Hello World"

In summary, @title(text: String) capitalizes all words in a String.

The <h1>@title("hello world")</h1> is how you could ouput the result in a ScalaTemplate.

Upvotes: 3

Related Questions