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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With