代码之家  ›  专栏  ›  技术社区  ›  Mario Ishac

如何允许更精确类型的使用者作为不太精确类型的使用者传入?

  •  1
  • Mario Ishac  · 技术社区  · 7 年前

    我有以下两个功能接口:

    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 ,因此任何抽象都变得更加困难。

    2 回复  |  直到 7 年前
        1
  •  3
  •   talex    7 年前

    这是我为你发明的。

    定义

    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);
    });
    
        2
  •  2
  •   Holger    7 年前

    不更改类型层次结构(例如,中建议的方式 this answer ),自适应步骤是不可避免的,因为 IndexBytePairConsumer IndexIntPairConsumer 是两种不同的类型。最小的适应步骤是

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

    正如您在问题中所说,int的使用者可以接受字节,因此 accept an的方法 IndexIntPairConsumer索引 是方法引用的有效目标,其中 IndexBytePairConsumer索引 应为。