小编juk*_*kzi的帖子

为什么在编译时不检查lambda返回类型?

使用的方法引用具有返回类型Integer。但是String在下面的示例中,允许不兼容。

如何解决方法with声明以确保方法引用类型安全而无需手动强制转换?

import java.util.function.Function;

public class MinimalExample {
  static public class Builder<T> {
    final Class<T> clazz;

    Builder(Class<T> clazz) {
      this.clazz = clazz;
    }

    static <T> Builder<T> of(Class<T> clazz) {
      return new Builder<T>(clazz);
    }

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

  }

  static public interface MyInterface {
    Integer getLength();
  }

  public static void main(String[] args) {
// missing compiletimecheck is inaceptable:
    Builder.of(MyInterface.class).with(MyInterface::getLength, "I am NOT an Integer");

// compile time …
Run Code Online (Sandbox Code Playgroud)

java generics lambda type-inference method-reference

38
推荐指数
3
解决办法
1616
查看次数

为什么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
查看次数