简体   繁体   English

Java:具有泛型函数参考的编译错误

[英]Java: compilation error with generic function reference

Could someone help me to fix this compilation error, please? 有人可以帮我解决此编译错误吗?

I 'd like to define a map method in the generic interface called Suite and use it like this: 我想在称为Suite的通用接口中定义一个map方法,并像这样使用它:

Suite < Integer > suite2 = Suite.from("34", "78", "23").map(Integer::parseInt);

assertEquals(3, suite.size());
assertEquals(34, (int)suite.get(0));
assertEquals(78, (int)suite.get(1));
assertEquals(23, (int)suite.get(2));

The the call to the same method with a function and parameter compile well: 对具有函数和参数的相同方法的调用编译良好:

Suite<Integer> suite1 = Suite.from(1, 2).map(x -> x * 2);

assertEquals(2, suite.size());
assertEquals(2, (int)suite.get(0));
assertEquals(4, (int)suite.get(1));

So I've defined the method in the interface like this 所以我在这样的界面中定义了方法

public interface Suite<E> {

    public <E> Suite<E> map(int i, Function<? super E, ? extends E> f);
}

Note: this is almost the same protytype as the map method of Stream class (except the paramter i ) 注意:这几乎与Stream类的map方法具有相同的原型(参数i除外)。

My problem is in my test, this line does not compile: 我的问题是在测试中,此行无法编译:

map(Integer::parseInt)

because of these errors: 由于这些错误:

  • The type Integer does not define toString(Object) that is applicable here. Integer类型未定义此处适用的toString(Object)
  • Type mismatch: cannot convert Suite<Object> to Suite<String> 类型不匹配:无法将Suite<Object>转换为Suite<String>

I'm tried to redefine the function with a Supplier<E> but it does not work. 我试图用Supplier<E>重新定义该功能,但是它不起作用。

 Function<? super E, ? extends E> function

Integer is not a super class of String, hence this fails: 整数不是String的超类,因此失败:

Suite <String> suite1 = Suite.span(1, Integer::toString);

reference: Difference between <? 参考: 区别<? super T> and <? 超级T>和<? extends T> in Java 在Java中扩展T>

Usually functional mapping expects type changing, eg argument and result types are diverged: 通常,函数映射期望类型更改,例如,参数和结果类型是不同的:

https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#map-java.util.function.Function- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#map-java.util.function.Function-

Suite < Integer > suite2 = Suite.from("34", "78", "23").map(Integer::parseInt); Suite <Integer> suite2 = Suite.from(“ 34”,“ 78”,“ 23”)。map(Integer :: parseInt);

Here you change String type to Integer , thus you can't use common E generic name like 在这里,您将String类型更改为Integer ,因此您不能使用通用的E通用名称,例如

public <E> Suite<E> map(int i, Function<? super E, ? extends E> f);

but: 但:

public <T, R> Suite<R> map(int i, Function<? super T, ? extends R> f);

or: 要么:

public interface Suite<E> {
    public <R> Suite<R> map(int i, Function<? super E, ? extends R> f);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM