gpt4 book ai didi

java - 如何允许更精确类型的消费者作为不太精确类型的消费者传入?

转载 作者:行者123 更新时间:2023-11-29 07:25:35 24 4
gpt4 key购买 nike

我有以下两个功能接口(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 的消费者可以接受字节)? 我需要使用方法签名中的基元而不是相关的类,例如 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);
});

关于java - 如何允许更精确类型的消费者作为不太精确类型的消费者传入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53736596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com