You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@freemarker.apache.org by "Thomas Weidner (JIRA)" <ji...@apache.org> on 2016/12/07 08:54:58 UTC

[jira] [Created] (FREEMARKER-43) Consider adding a Java 8 Style forEach method to TemplateCollectionModel/TemplateSequenceModel

Thomas Weidner created FREEMARKER-43:
----------------------------------------

             Summary: Consider adding a Java 8 Style forEach method to TemplateCollectionModel/TemplateSequenceModel
                 Key: FREEMARKER-43
                 URL: https://issues.apache.org/jira/browse/FREEMARKER-43
             Project: Apache Freemarker
          Issue Type: Improvement
          Components: engine
    Affects Versions: 2.3.25-incubating
            Reporter: Thomas Weidner
            Priority: Minor


I have a lot of "tuple-like" types in my model. For example:
{code:java}
class Tuple {
  int a;
  float b;
  String c;
}
{code}
In the template, i would like to iterate through the components of tuple using #list. To implement TemplateSequenceModel or TemplateCollectionModel, I basically need to create a temporary List object from the tuple, which seems unnecessary. 

Java 8 added a forEach model to java.lang.Iterable, which could be easily implemented for Tuple without temporary objects:
{code:java}
// in Tuple
void forEach(Consumer<Object> c) {
  c.accept(a);
  c.accept(b);
  c.accept(c);
}
{code}
Unfortunately, there is no such method in TemplateSequenceModel/TemplateCollectionModel.

I propose to add such a method to the both classes and use this method in IteratorBlock instead of handcrafted iteration. This would allow to more efficient iteration for custom classes, while not imposing worse performance on "standard" collections/interfaces (these also provide forEach in java8). 

As this change would require java8, this API change would not break existing implementations of Template*Model, as forEach could be implemented as default interface method.

I could provide a prototype patch if requested.

Maybe as a separate bug, Template{Collection,Sequence}Model should both inherit from a new TemplateIterableModel which only provides forEach.



--
This message was sent by Atlassian JIRA
(v6.3.4#6332)