Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a new ListChangeListener<Item>() with lambda?

How do I write a new ListChangeListener() with lambda in java8?

listItems.addListener(new ListChangeListener<Item>() {
    @Override
    public void onChanged(
        javafx.collections.ListChangeListener.Change<? extends Item> c) {
        // TODO Auto-generated method stub
    }
});

This is what I tried:

listItems.addListener(c->{});

But eclipse states:

The method addListener(ListChangeListener) is ambiguous for the type ObservableList.

The List is declared as:

ObservableList<Item> listItems = FXCollections.observableArrayList();
like image 246
simonides Avatar asked Apr 28 '14 07:04

simonides


People also ask

What is lambda expression in Java 8 with example?

Lambda Expressions were added in Java 8. A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

What is the return type of lambda expression?

The body of a lambda expression can contain zero, one, or more statements. When there is a single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression.


1 Answers

Since ObservableList inherits addListener(InvalidationListener) from the Observable interface, the compiler is unable to determine which version to call. Specifying the type of the lambda through a cast should fix this.

listItems.addListener((ListChangeListener)(c -> {/* ... */}));

You can also explicitly specify the type of c:

listItems.addListener((ListChangeListener.Change<? extends Item> c) -> {/* ... */});
like image 123
Andrew Vitkus Avatar answered Oct 09 '22 23:10

Andrew Vitkus