Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

java - How to initialize field using lambda

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();

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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).

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...