如何允许更精确类型的使用者作为不太精确类型的消费者传递



我有以下两个功能接口:

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的使用者可以接受字节(我需要在方法签名中使用基元,而不是相关的类,如IntegerByte,因此任何抽象都变得更加困难。

这是我为你发明的东西。

定义

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);
});

在不改变类型层次结构(例如,本答案中建议的方式(的情况下,自适应步骤是不可避免的,因为IndexBytePairConsumerIndexIntPairConsumer是两种不同的类型。最小的适应步骤是

// given
IndexIntPairConsumer consumer = …
// call as
forEachIndexValuePair(consumer::accept);

正如您在问题中所说,int的使用者可以接受字节,因此IndexIntPairConsumeraccept方法是预期IndexBytePairConsumer的方法引用的有效目标。

最新更新