Vinko Vorih
Vinko Vorih

Reputation: 31

replacing null declaration with Optional java

I'm having hard time with understanding of Optional class. So, I have a task where I need to replace every null initialization with Optional class.

e.g.

I have a class Client

So I made object like this:

Client chosen = null;

How am I supposed to replace that null initialization with Optional?

Upvotes: 2

Views: 4121

Answers (2)

E. Bavoux
E. Bavoux

Reputation: 555

You have two simple solutions to initialize the Optional in your case:

  1. Initialize the Optional directly to empty, as described by cwschmidt:

    Optional<Client> chosen = Optional.empty();
    
  2. Initialize the Optional, after the POJO has been initialized or not:

    Optional<Client> chosen = Optional.ofNullable(client)
    

    --> If client is null, the Optional chosen will be inititialized to empty, and if client has a value it will be initialized.

Upvotes: 1

cwschmidt
cwschmidt

Reputation: 1204

Your initialization could look like the following:

Optional<Client> chosen = Optional.empty(); 

or if you want to assign an initial value:

Client client = new Client();
Optional<Client> chosen = Optional.of(client); 

Upvotes: 5

Related Questions