Elias Johannes Elias Johannes -4 years ago 88
Scala Question

Comparing three Scala lists in Play Framework templates

I'm trying to filter three lists of objects and output them in a loop, I use PlayFramework and i got Java running in the backend, i only use Scala templates in my front end.

Let's assume the following:
I got 3 lists now:

AList
,
BList
,
CList

List A and C don't have anything in common, but list B is the linking List in the middle, who acts as a connection. List C contains objects with two attributes:
idA
and
idC
. Now i want to receive all objects from
AList
and if it's ID exist in
BList
i want to display additional information coming from
CList
. I don't really have a clue how to approach this in scala. I read some threads about zipping lists together and came up with an approach like this:

@listCheckA = @{
AList.map(a => (a, BList.map(_.idA).contains(a.idA)))
}
@listCheckC = @{
CList.map(c => (c, BList.map(_.idC).contains(c.idC)))
}
@listLinked = @{
listCheckA.zip(listCheckC).map( ??? )
}


Afterwards i want to output the objects with a
for
loop.
If this might be a legit approach, what should i do at the listLinked to check my conditions?

Sorry if this question might sound dumb, I hardly used Scala before.

Thanks in advance!

Answer Source

First of all, this looks a lot like a many-to-may link table, which you should be able to handle using your DB library, something like

SELECT a.*, c.* FROM TableA as a, TableB as b, TableC as c WHERE a.idA = b.idA AND c.idC = b.idC`

If you really need to do this using scala (as I said in your previous thread, logic should not be in templates, but rather in your controller), you can do it as a for comprehension:

@for {
  a <- AList
  b <- BList if b.aid == a.aid
  c <- CList if c.cid == b.cid
} {
  // ... do whatever you want with a and b and c here ...
}

This is the same as three for loops inside one another, except that the if statements will do what it says (filter elements which satisfy the predicate).

You will find it difficult to do this more efficiently, unless you use a SQL statement as above to query directly in your DB.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download