在lambda上输入推断 [英] Type inference on lambdas

查看:132
本文介绍了在lambda上输入推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在转换一些代码以使用Java 8功能。在下面的设计示例中

I have been converting some code to use Java 8 features. In the following contrived example

    Arrays.asList("1", "2", "3", "cheese", "5").stream().map(line -> {
        try {
            return Optional.of(Integer.parseInt(line));
        } catch (NumberFormatException xep) {
            return Optional.empty();
        }
    }).forEach( v -> 
        System.out.println(v.orElse(999))
    );

(意图是将一些字符串解析为整数并用999替换任何不可解析的值)

(the intention is to parse some strings as ints and replace any unparseable values with 999)

编译器报告

error: incompatible types: int cannot be converted to CAP#1
System.out.println(v.orElse(999))
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ? extends Object"

我尝试将999转换为整数或对象但没有成功。

I've tried casting 999 to an Integer or Object with no success.

似乎真正的问题是第一个lambda的推断返回类型是可选< Object> 而不是可选<整数>

It seems that the real problem is that the inferred return type of the first lambda is Optional<Object> and not Optional<Integer>

如果我这样做

    Arrays.asList("1", "2", "3", "cheese", "5").stream().map(line -> {
        Optional<Integer> ans;
        try {
            ans = Optional.of(Integer.parseInt(line));
        } catch (NumberFormatException xep) {
            ans = Optional.empty();
        }
        return ans;
    }).forEach( v -> 
        System.out.println(v.orElse(999))
    );

它运作完美,但不太优雅。有没有更好的方法来引导编译器我想要的返回类型?

it works perfectly, but not quite as elegant. Is there a better way to 'guide' the compiler to the return type that I want?

推荐答案

一个简单的修复是使用目标类型:

A simple fix is to use a target type:

return Optional.<Integer> empty();

另外我注意到你使用 Integer.parseInt 返回 int ,因此您还可以使用 OptionalInt 来解决您的问题并保存装箱操作:

Also I note that you use Integer.parseInt which returns an int, so you could also use an OptionalInt which will solve your problem and save a boxing operation:

try {
  return OptionalInt.of(Integer.parseInt(line));
} catch (NumberFormatException xep) {
  return OptionalInt.empty();
}

这篇关于在lambda上输入推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆