|
2 | 2 |
|
3 | 3 | ## Optional |
4 | 4 |
|
5 | | -## Introduction |
| 5 | +The **Optional<T>** type was introduced in Java 8 as a way to indicate that a method _may_ return a value. |
6 | 6 |
|
7 | | -The **Optional<T>** type was introduced in Java 8 as a way to indicate that a method will return an object of type T or an empty value. It is present in type signatures of many core Java methods. |
8 | | -Before Java 8, developers had to implement null checks: |
| 7 | +In other words, there is a chance the method returns "no value" at all. |
| 8 | + |
| 9 | +## Creating an Optional<T> object |
| 10 | + |
| 11 | +Given an object of type Employee, an Optional<Employee> object is created as follows: |
9 | 12 |
|
10 | 13 | ```java |
11 | | -public Employee getEmployee(String name) { |
12 | | - // Assume that getEmployeeByName retrieves an Employee from a database |
13 | | - Employee employee = getEmployeeByName(name); |
14 | | - if (employee != null) { |
15 | | - return employee; |
16 | | - } else { |
17 | | - throw new IllegalArgumentException("Employee not found"); |
18 | | - } |
19 | | -} |
| 14 | +Employee employee = new Employee(); |
| 15 | +Optional<Employee> optionalEmployee = Optional.of(employee); |
20 | 16 | ``` |
21 | 17 |
|
22 | | -With the Optional API, the code above can be simplified to: |
| 18 | +`optionalEmployee` is a wrapper of `employee`. |
| 19 | + |
| 20 | +TBD: explain empty, present and get. |
| 21 | + |
| 22 | +## Usage |
23 | 23 |
|
24 | 24 | ```java |
25 | 25 | public Optional<Employee> getEmployee(String name) { |
@@ -62,8 +62,3 @@ public Optional<Integer> getEmployeeAge(String name) { |
62 | 62 | .orElse("No employee found"); |
63 | 63 | } |
64 | 64 | ``` |
65 | | - |
66 | | -It is important to understand that the Optional API does not eliminate the null checking, |
67 | | -but it defers it until the end of a series of methods, as long as all those methods return an optional object. |
68 | | -The Optional type is mainly used as returned type. Using it as a parameter type or field type is less common and |
69 | | -not recommended, as explained by one well-known Java language architect in [this SO answer](https://stackoverflow.com/questions/26327957/should-java-8-getters-return-optional-type) |
0 commit comments