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

标签 java primitive primitive-types functional-interface pecs

我有以下两个功能接口(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/

相关文章:

java - StartTimePicker 设置时间(android)

java - 带有 spring 的拦截器 - 上下文初始化失败

C# 通过 Delegate.CreateDelegate 使用具有值类型的属性

java - 添加非原始类型数据作为节点和关系中的属性值

C# 对象初始化程序将初始化只读属性,但仅适用于非原始类型

iphone - 声明基本类型属性

java - 类转换异常 : java. lang.String 与 [Ljava.lang.Object; 不兼容;

java - 使用 Windows 在 jar 库上使用 System.loadLibrary

iphone - 在 Objective C 中声明、属性、合成和实现 int[] 数组

c++ - 如果 int 不是类,为什么 int x = int(5) 合法?