Limited general options in the Play Framework template

How to use limited general options in a Scala template in a Play Framework 2.3 Java project?

I currently have something like:

@(entities: List[_ <: Entity], currentEntity: Entity)

<ul>
    @for(entity <- entities) {
        @if(currentEntity.equals(entity)) {
            <li><strong>@entity</strong></li>
        } else {
            <li>@entity</li>
        }
    }
</ul>

However, I can call it different types of objects in entitiesand currentEntity- which is not very nice. I would like to do something like:

@[T <: Entity](entities: List[T], currentEntity: T)
...

But this gives me a Invalid '@' symbolcompilation error.

+4
source share
1 answer

As @mz points out, it is not supported (yet). But you can get the required type safety (at the expense of another family of classes) by first creating arguments to an object of the form:

case class HighlightedListView[E <: Entity](entities:List[E], currentEntity:E)

HighlightedListView :

 def foo = Action {
  ...
  // Assuming some SubEntity exists, the compiler will enforce the typing:
  val hlv = HighlightedListView[SubEntity](entities, currentEntity)


  Ok(html.mytemplate(hlv))

}

, barf, . , , :

@(hlv:HighlightedListView[_])

<ul>
    @for(entity <- hlv.entities) {
        @if(hlv.currentEntity.equals(entity)) {
            <li><strong>@entity</strong></li>
        } else {
            <li>@entity</li>
        }
    }
</ul>

View , :

case class HighlightedListView[E <: Entity](entities:List[E], currentEntity:E) {
   def shouldHighlight(e:Any):Boolean = currentEntity.equals(e)
}

:

 @if(hlv.shouldHighlight(entity)) {
     <li><strong>@entity</strong></li>
 } else {
     <li>@entity</li>
 }
+3

All Articles