title: Play Framework 2 - Scala template: How to call a specific method on a generic object?
body: <p>I am using Play Framework 2.1.5 in a Java application.</p>
  
  <p>I've got a view component that takes a list of generic objects as a parameter. In this component, I want to iterate on the list and get some properties of each element.</p>
  
  <p>This would look like something like this:</p>
  
  <pre><code>@(elements: List[_])
  
  @for((element, i) &lt;- elements.view.zipWithIndex) {
      @i
      @element.id
      @element.name
  }
  </code></pre>
  
  <p>(I need those 3 values)</p>
  
  <p>But, of course, <code>element.id</code> and <code>element.name</code> would not compile even if the type of objects I put in the list contained these methods. So I did this:</p>
  
  <pre><code>@for((element, i) &lt;- elements.view.zipWithIndex) {
      @defining(
          ViewsUtils.getGenericElementId(element),
          ViewsUtils.getGenericElementName(element)) {
              case (id, name, something) =&gt;
                  @i
                  @id
                  @name
          }
  }
  </code></pre>
  
  <p>And in a Java utility class:</p>
  
  <pre><code>public final class ViewsUtils {
  
      public static String getGenericElementId(Object object) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
          return object.getClass().getMethod("getId").invoke(object).toString();
      }
  
      public static String getGenericElementName(Object object) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
          return object.getClass().getMethod("getName").invoke(object).toString();
      }
  }
  </code></pre>
  
  <p>This works but I know it's not right because it could throw a RuntimeException in case one of these methods didn't exist for the type of object I put in the list.</p>
  
  <p>Here are my suppositons:</p>
  
  <ol>
  <li><p>Casting the elements</p></li>
  <li><p>Using inheritance</p></li>
  <li><p>As I just need 2 properties of each object (id and name), I could use a map, but I need the index of the loop (is it possible to get it from a map?) and it wouldn't work if I needed more than 2 properties.</p></li>
  <li><p>Maybe Scala provides the syntax for this kind of stuff.</p></li>
  </ol>
  
  <p>Or maybe I'm just looking in the wrong direction.</p>
  
  <p>Thank you for your help.</p>