![]() Home |
![]() Back |
![]() Contents |
![]() Next |
x -> ...,
(a, b) -> ..., (Type a) -> ... - and use them
as a functional-interface value in Java code, usually without an explicit
cast. Method references (Foo::bar) are not supported.
Function expr = x -> x + 1;
Function block = x -> { return x + 1; };
Supplier zeroArg = () -> 5;
Function oneArg = x -> x * 2;
BiFunction twoArgs = (a, b) -> a + b;
Function typedArg = (Integer x) -> x + 10;
expr.apply(1); // 2
twoArgs.apply(2, 3); // 5
|
Collection.forEach(),
Collections.sort(), or a Stream pipeline:
sum = 0;
Arrays.asList(1, 2, 3).forEach( x -> { sum += x; } );
sorted = new ArrayList(Arrays.asList(3, 1, 2));
Collections.sort( sorted, (a, b) -> a - b );
mapped = Arrays.asList(1, 2, 3).stream()
.map( x -> x * 2 )
.collect( Collectors.toList() );
|
Object variable just like any other BeanShell value.
counter = 1; Supplier getCounter = () -> counter; counter = 2; getCounter.get(); // 2 |
| Note: Because BeanShell does not refresh a for-each loop variable per iteration the way Java does, a lambda created inside a loop captures the same variable across iterations, not a fresh one each time:
for ( String s : list )
list2.add( () -> s ); // every lambda here returns list's LAST element
If you need each lambda to see a different value, assign
it to a fresh local inside the loop body first.
|
bsh.RuntimeEvalError
instead.
Predicate.negate()) is
unaffected.Supplier
can't be fully type-checked at conversion time, so a Java
caller expecting Supplier<String> may still
see a ClassCastException at the point of use.Serializable interface serializes
normally, but deserializing it throws rather than running - the same
rule that already applies to serialized 'this' references - because
deserialization has to freshly initialize the named interface.
![]() Home |
![]() Back |
![]() Contents |
![]() Next |