vendredi 20 novembre 2015

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

Aucun commentaire:

Enregistrer un commentaire