2

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?

2 Answers 2

5

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); 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.