Nested function: Difference between revisions

Content added Content deleted
(draft task -> task)
(Java)
Line 136: Line 136:
3. third
3. third
</lang>
</lang>

=={{header|Java}}==
{{works with|Java|8}}

Since version 8, Java has limited support for nested functions. All variables from the outer function that are accessed by the inner function have to be _effectively final_. This means that the counter cannot be a simple <tt>int</tt> variable; the closest way to emulate it is the <tt>AtomicInteger</tt> class.

<lang java>import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;

public class NestedFunctionsDemo {

static String makeList(String separator) {
AtomicInteger counter = new AtomicInteger(1);

Function<String, String> makeItem = item -> counter.getAndIncrement() + separator + item + "\n";

return makeItem.apply("first") + makeItem.apply("second") + makeItem.apply("third");
}

public static void main(String[] args) {
System.out.println(makeList(". "));
}
}</lang>


=={{header|JavaScript}}==
=={{header|JavaScript}}==