Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java lambda expressions - explicit target type

Consider functional interfaces A and B extends A. Is it possible to create an instance implementing not only A but also B with a lambda expression when only A is required?

Example:

interface A {
    void foo();
}

interface B extends A {}

void bar(A arg) {
    System.out.println(arg instanceof B);
}

/* somewhere in a block */
    bar( () -> {} ); // Prints "false"

How could I call bar(A) so that it prints true?

I would find this useful in event listeners, where subinterfaces could specify additional data about the listener, e.g. if a Listener also implements ConcurrentListener, it is invoked concurrently.

like image 293
OLEGSHA Avatar asked Dec 23 '22 06:12

OLEGSHA


1 Answers

Simply do a cast to tell the compiler the type you want:

A a = (B)() -> someAction();
System.out.println(a instanceof B); // true

I would find this useful in event listeners, where subinterfaces could specify additional data about the listener, e.g. if a Listener also implements ConcurrentListener, it is invoked concurrently.

That sounds like bad design (though I can't explain why...). Maybe you could have a isConcurrent method in the interface that implementers need to implement?

like image 136
Sweeper Avatar answered Jan 10 '23 16:01

Sweeper