Reputation: 31
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
Reputation: 555
You have two simple solutions to initialize the Optional in your case:
Initialize the Optional directly to empty, as described by cwschmidt:
Optional<Client> chosen = Optional.empty();
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
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