Reputation: 2354
I've worked around with Play Framework for a while but I'm almost new to Scala Templates . For me as a C-familiar language developer sometimes it looks a bit strange
I was wondering if someone here could help me understand this code better I took it from http://www.playframework.com/documentation/2.2.x/JavaGuide3 (Zentask Example)
@(projects: List[Project], todoTasks: List[Task])
@main("Welcome to Play") {
<header>
<hgroup>
<h1>Dashboard</h1>
<h2>Tasks over all projects</h2>
</hgroup>
</header>
<article class="tasks">
@todoTasks.groupBy(_.project).map {
case (project, tasks) => {
<div class="folder" data-folder-id="@project.id">
<header>
<h3>@project.name</h3>
</header>
<ul class="list">
@tasks.map { task =>
<li data-task-id="@task.id">
<h4>@task.title</h4>
@if(task.dueDate != null) {
<time datetime="@task.dueDate">
@task.dueDate.format("MMM dd yyyy")</time>
}
@if(task.assignedTo != null && task.assignedTo.email != null) {
<span class="assignedTo">@task.assignedTo.email</span>
}
</li>
}
</ul>
</div>
}
}
</article>
}
This 3 lines are really confusing for me :
@todoTasks.groupBy(_.project).map {
case (project, tasks) => {
@tasks.map { task =>
I do appreciate if anyone can explain me in more details what exactly these 3 lines are doing?
Thanks guys
Upvotes: 4
Views: 1256
Reputation: 1470
Okay, so there are several transformations going on here.
@todoTasks.groupBy(_.project)
says that a todoTask has a field called project
, and we should transform that list of todoTasks into a Map where the project is the key and the values are all todoTasks that match the key.
.map { case (project, tasks) => {
says that we now have a Map where the key is project
and the value is a list of tasks
. And if we have those two items (project, tasks), then we should do something with each task, the something is to what follows the =>
tip, you don't need to have a deep knowledge of scala to be productive as a java play developer, just do your transformations of the data in your java controller.
Upvotes: 2
Reputation: 1010
I don't think these are specific to Play templates at all, but rather examples of idiomatic functional Scala. The middle line uses pattern matching with an anonymous function, which is covered very nicely by this tutorial. The other two are calling functions on collections that take functions themselves as parameters. These are called "higher order functions" and are one of the key tools of functional programming. .map, in particular, is key to FP. Daniel Spiewak's Scala Collections For The Easily Bored series is a great place to get started on functions such as these.
Upvotes: 1