我有以下两个功能接口(interface):
IndexBytePairConsumer.java
package me.theeninja.nativearrays.core;
@FunctionalInterface
public interface IndexBytePairConsumer {
void accept(long index, byte value);
}
IndexIntPairConsumer.java
package me.theeninja.nativearrays.core;
@FunctionalInterface
public interface IndexIntPairConsumer {
void accept(long index, int value);
}
我还有以下方法:
public void forEachIndexValuePair(IndexBytePairConsumer indexValuePairConsumer) {
...
}
有什么方法可以让 IndexIntPairConsumer
在上述方法中传递(因为 int 的消费者可以接受字节)? 我需要使用方法签名中的基元而不是相关的类,例如 Integer
和 Byte
,因此任何抽象都变得更加困难。
最佳答案
这是我为你发明的。
定义
public interface IndexBytePairConsumer {
void accept(long index, byte value);
}
public interface IndexIntPairConsumer extends IndexBytePairConsumer {
default void accept(long index, byte value) {
this.accept(index, (int) value);
}
void accept(long index, int value);
}
你可以使用它
IndexIntPairConsumer c = (a,b)->{
System.out.println(a + b);
};
forEachIndexValuePair(c);
forEachIndexValuePair((a, b) -> {
System.out.println(a + b);
});
关于java - 如何允许更精确类型的消费者作为不太精确类型的消费者传入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53736596/