Unexpected variable ... is already defined ...

Remi Forax forax at univ-mlv.fr
Wed Dec 26 05:50:57 PST 2012


On 12/26/2012 02:39 PM, Denis DEBARBIEUX wrote:
> Hi,
>
> In the following example, I embed two functions:
> /event -> event.match(event -> "a".equals(event.label))/
>
> I got an error "variable event is already defined".
>
> I am surprise about that. Is-it expected?

Yes, it's surprising but it's what is currently specified.
A parameter of a lambda can not hide a parameter/local variable of its 
enclosing scope.

>
> If yes, can the inner function (that does the test) use the outer
> parameter event?

yes, you can capture the value of parameters and local variables if they 
are effectively final (not assigned more than once).

>
> Denis
> Bonus question: does a short syntax exist to code f.apply (f is function).

No.

cheers,
Rémi

>
> //public class Main {//
> //
> //    public static void main(String[] args) {//
> //        System.out.println("start");//
> ////
> //        // Function<Event, Boolean> test = (event ->
> "a".equals(event.label));//
> //        // Function<Event, MatchEvent> matcher = (event ->
> event.match(test));//
> ////
> //        getStream().map(event -> event.match(_event ->
> "a".equals(_event.label))).forEach(System.out::println); // OK//
> //        getStream().map(event -> event.match(event ->
> "a".equals(event.label))).forEach(System.out::println); // KO//
> ////
> //        System.out.println("end");//
> //    }//
> //
> //    private static Stream<Event> getStream() {//
> //        List<Event> stream = new ArrayList<>();//
> //        stream.add(new Event("a"));//
> //        stream.add(new Event("b"));//
> //         return stream.stream();//
> //    }//
> //
> //}//
> //
> //class Event {//
> ////
> //    final String label;//
> //
> //    public Event(String label) {//
> //        super();//
> //        this.label = label;//
> //    }//
> ////
> //    MatchEvent match(Function<Event, Boolean> f) {//
> //        // question: short synaxe for apply?//
> //        return new MatchEvent(this, f.apply(this));//
> //    }//
> //
> //    @Override//
> //    public String toString() {//
> //        return "Event [label=" + label + "]";//
> //    }//
> ////
> ////
> ////
> //}//
> //
> //class MatchEvent {//
> ////
> //    final Event event;//
> //    final boolean match;//
> ////
> //    public MatchEvent(Event event, boolean match) {//
> //        super();//
> //        this.event = event;//
> //        this.match = match;//
> //    }//
> //
> //    @Override//
> //    public String toString() {//
> //        return "MatchEvent [event=" + event + ", match=" + match + "]";//
> //    }//
> ////
> //}/
>
>



More information about the lambda-dev mailing list