相关疑难解决方法(0)

为什么Java无法推断超类型?

大家都知道龙延伸Number。那么为什么不编译呢?

以及如何定义方法with,使程序无需任何手工转换就可以编译?

import java.util.function.Function;

public class Builder<T> {
  static public interface MyInterface {
    Number getNumber();
    Long getLong();
  }

  public <F extends Function<T, R>, R> Builder<T> with(F getter, R returnValue) {
    return null;//TODO
  }

  public static void main(String[] args) {
    // works:
    new Builder<MyInterface>().with(MyInterface::getLong, 4L);
    // works:
    new Builder<MyInterface>().with(MyInterface::getNumber, (Number) 4L);
    // works:
    new Builder<MyInterface>().<Function<MyInterface, Number>, Number> with(MyInterface::getNumber, 4L);
    // works:
    new Builder<MyInterface>().with((Function<MyInterface, Number>) MyInterface::getNumber, 4L);
    // compilation error: Cannot infer ...
    new Builder<MyInterface>().with(MyInterface::getNumber, 4L);
    // compilation …
Run Code Online (Sandbox Code Playgroud)

java type-inference

19
推荐指数
2
解决办法
1195
查看次数

Why is a type parameter stronger then a method parameter

Why is

public <R, F extends Function<T, R>> Builder<T> withX(F getter, R returnValue) {...}
Run Code Online (Sandbox Code Playgroud)

more strict then

public <R> Builder<T> with(Function<T, R> getter, R returnValue) {...}
Run Code Online (Sandbox Code Playgroud)

This is a follow up on Why is lambda return type not checked at compile time. I found using the method withX() like

.withX(MyInterface::getLength, "I am not a Long")
Run Code Online (Sandbox Code Playgroud)

produces the wanted compile time error:

The type of getLength() from the type BuilderExample.MyInterface is long, this is incompatible with the descriptor's return type: …

java generics lambda type-inference

12
推荐指数
1
解决办法
258
查看次数

标签 统计

java ×2

type-inference ×2

generics ×1

lambda ×1