如何使用lambda初始化字段 [英] How to initialize field using lambda

查看:490
本文介绍了如何使用lambda初始化字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个ConnectionFactory类型的实例字段。
供应商可以这样做:

I need an instance field of type ConnectionFactory. A supplier can do it:

private Supplier<ConnectionFactory> connectionFactorySupplier = () -> {
    // code omitted
    return null;
};

private ConnectionFactory connectionFactory = connectionFactorySupplier.get();

它可以缩短为一行,如下所示:

It can be shortened to one line like so:

private ConnectionFactory connectionFactory = new Supplier<ConnectionFactory>() {
    @Override
    public ConnectionFactory get() {
        // code omitted
        return null;
    }
}.get();

使用lambda有没有办法让它更简洁一些?我尝试过以下但不编译:

Is there a way to make this a bit less verbose, using lambda? I've tried the following but it doesn't compile:

private ConnectionFactory connectionFactory= () -> {
    // code omitted
    return null;
}.get(); 
// Compilation failure
// error: lambda expression not expected here


推荐答案

最后一个片段中的问题是编译器无法猜测

The problem in your last snippet is that there is no way for the compiler to guess that

() -> { 
// code omitted
    return null;
}

是实现的SAM的lambda表达式供应商界面(似乎你首先错过了表达式的括号,但无论如何)。

is a lambda expression that implements the SAM of the Supplier interface (and it seems you missed parentheses around the expression in the first place, but anyway).

你可以做的事情是转换lambda以告诉编译器这实际上是您实现的 Supplier 接口的抽象方法:

The thing you could do is to cast the lambda in order to tell the compiler that this is actually the abstract method of the Supplier interface that you implement:

private ConnectionFactory connectionFactory = 
     ((Supplier<ConnectionFactory>)() -> {
         // code omitted
         return null;
     }).get();

但是你得到的是什么,而不是有一个初始化器

But then what do you gain with that instead of having an initializer

private ConnectionFactory connectionFactory;
{
    //code omitted
    connectionFactory = null;
}

或初始化构造函数内的连接或使用最终方法:

or initialize the connection within the constructor or with a final method:

private ConnectionFactory connectionFactory = initConnection();

private final ConnectionFactory initConnection() {
    //code omitted
    return null;
}

这篇关于如何使用lambda初始化字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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