如何让更精确类型的消费者作为不太精确类型的消费者传入?

我有以下两个功能接口:


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在上述方法中传递一个(因为整数的消费者可以接受字节)?我需要在方法签名中使用原语而不是关联的类,例如Integerand Byte,因此任何抽象都变得更加困难。


一只萌萌小番薯
浏览 128回答 2
2回答

烙印99

这是我为你发明的。定义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);});

森栏

在不更改类型层次结构的情况下(例如,此答案中建议的方式),适应步骤是不可避免的,因为IndexBytePairConsumer它们IndexIntPairConsumer是两种不同的类型。最小的适应步骤是// givenIndexIntPairConsumer consumer = …// call asforEachIndexValuePair(consumer::accept);正如您在问题中所说,int 的使用者可以接受字节,因此acceptan的方法是预期IndexIntPairConsumeran 的方法引用的有效目标。IndexBytePairConsumer
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java