3

I am working on a way to generalize some HTML formatting code so I created a simple static method:

@SafeVarargs
public static <T> String table(List<T> data, Function<T, Object> link, Function<T, Object> ... cols) {
  StringBuilder html = new StringBuilder();
  for(T item : data) {
    html.append("<tr>\n");
    html.append("  <th><a href='").append(link.apply(item)).append("' class='btn btn-default btn-sm'>open</a></th>\n");
    for(Function<T, Object> col : cols) {
      html.append("  <td>").append(col.apply(item)).append("</td>\n");
    }
    html.append("</tr>\n");
  }

  return html.toString();
}

When I run it with 3 arguments like this:

public static void main(String ... args) {
  List<SOTestModel> data = new ArrayList<SOTestModel>();
  data.add(new SOTestModel(1, "Adam", DateTime.now().minusYears(35)));
  data.add(new SOTestModel(2, "Bob", DateTime.now().minusYears(33)));
  data.add(new SOTestModel(3, "Carl", DateTime.now().minusYears(30)));

  System.out.println(table(data, r->r.getId(), r->r.getName(), r->r.getCreated().toString("YYYY-MM-dd")));
}

I get the following output:

<tr>
  <th><a href='1' class='btn btn-default btn-sm'>open</a></th>
  <td>Adam</td>
  <td>1980-04-13</td>
</tr>
<tr>
  <th><a href='2' class='btn btn-default btn-sm'>open</a></th>
  <td>Bob</td>
  <td>1982-04-13</td>
</tr>
<tr>
  <th><a href='3' class='btn btn-default btn-sm'>open</a></th>
  <td>Carl</td>
  <td>1985-04-13</td>
</tr>

However when I only pass one argument for the vararg like this:

public static void main(String ... args) {
  List<SOTestModel> data = new ArrayList<SOTestModel>();
  data.add(new SOTestModel(1, "Adam", DateTime.now().minusYears(35)));
  data.add(new SOTestModel(2, "Bob", DateTime.now().minusYears(33)));
  data.add(new SOTestModel(3, "Carl", DateTime.now().minusYears(30)));

  System.out.println(table(data, r->r.getId(), r->r.getName()));
}

I get the compiler error The target type of this expression must be a functional interface pointing to r->r.getName(). I can overcome this by adding a second table() function with the following signature (without the vararg):

public static <T> String table(List<T> data, Function<T, Object> link, Function<T, Object> col) {... same body ...}

But what I'm trying to understand is why?

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Jason Sperske
  • 29,816
  • 8
  • 73
  • 124

0 Answers0