Skip to content

Latest commit

Β 

History

History
62 lines (38 loc) Β· 1.82 KB

optional.md

File metadata and controls

62 lines (38 loc) Β· 1.82 KB

Optional 클래슀

λ‹€μŒμ„ importν•˜κ³  μ‚¬μš©ν•˜μž.

import java.util.Optional;

μ°Έμ‘°: https://jdm.kr/blog/234

의미

μžλ°”μ—μ„œλŠ” λ°˜ν™˜ νƒ€μž…μœΌλ‘œ Optional<T>을 μ‚¬μš©ν•  수 μžˆλ‹€.

이 Optional의 주된 νŠΉμ§•μ€ λ°”λ‘œ 'Null κ°’ λ°˜ν™˜μ— λŒ€μ‘'ν•˜λŠ” μ˜λ―Έκ°€ μžˆλ‹€.

μ˜ˆμ‹œ - ofNullable

전ꡭ에 μžˆλŠ” ν•΄μž₯κ΅­ 맀μž₯을 μ €μž₯ν•˜λŠ” κ°„λ‹¨ν•œ Map이 μžˆλ‹€κ³  ν•΄λ³΄μž.

맀μž₯의 고유 Idλ₯Ό 가지고 맀μž₯의 Store객체λ₯Ό λ°›μ•„μ˜€λŠ” ν•¨μˆ˜μ΄λ‹€.

Map<Long, Store> map = new HashMap<>();
public Optional<Store> findById(Long id) {
    return Optional.ofNullable(map.get(id));
}

λ¬Όλ‘  μ°ΎλŠ” Id에 ν•΄λ‹Ήν•˜λŠ” 맀μž₯ 객체가 μžˆμ–΄μ„œ μ •μƒμ μœΌλ‘œ 객체λ₯Ό λ°˜ν™˜ν•  μˆ˜λ„ μžˆλ‹€.

ν•˜μ§€λ§Œ λ°›μ•„μ˜¨κ²Œ NULLμΌμˆ˜λ„ μžˆλŠ”λ°, μ΄λ•Œ .ofNullable을 μ‚¬μš©ν•˜λ©΄ λ°œμƒν•˜λŠ” NullPointerException μ˜ˆμ™Έλ₯Ό 막을 수 μžˆλ‹€.

λ°˜ν™˜ν•œ 값이

  • Null이 μ•„λ‹ˆλ©΄
    • Store 객체λ₯Ό κ°€μ§€λŠ” Optional 객체 λ°˜ν™˜
  • Null이면
    • λΉ„μ–΄μžˆλŠ” Optional 객체 λ°˜ν™˜

Optional 클래슀의 λ©”μ†Œλ“œ

μœ„μ—μ„œ λ³΄μ•˜λ“―μ΄ Optional 객체 μ•ˆμ˜ 객체에 μ ‘κ·Όν•  μ†Œμš”κ°€ λ°œμƒν•˜λ©°,

μ΄λŠ” μ—¬λŸ¬κ°€μ§€ λ©”μ†Œλ“œλ₯Ό ν†΅ν•΄μ„œ μ΄λ£¨μ–΄μ§ˆ 수 μžˆλ‹€.

get()

μœ„μ—μ„œ λ³΄μ•˜λ“―μ΄ μ–΄μ°Œλ˜μ—ˆλ“  λ°˜ν™˜λ˜λŠ” 값은 Optional 객체이닀.

λ”°λΌμ„œ Optional μ•ˆμ˜ 객체에 μ ‘κ·Όμ„ν•΄μ•Όν•˜λŠ”λ°,

.get()을 μ‚¬μš©ν•˜λ©΄ μ•ˆμ— μžˆλŠ” 객체λ₯Ό κΊΌλ‚Ό 수 μžˆλ‹€.

μ˜ˆμ‹œ

μœ„μ—μ„œ μ •μ˜ν•œ findById(Ling id) λ©”μ†Œλ“œλ₯Ό μ‚¬μš©ν•œλ‹€κ³  κ°€μ •ν–ˆμ„λ•Œ,

public void output(Long id){
		Store store = findById(id).get();
}

findById의 λ°˜ν™˜ν˜•μ΄ Optional 객체이며, 이제 store 객체 μ•ˆμ— μ ν•©ν•œ κ°’ ν˜Ήμ€ Null 값이 λ“€μ–΄μžˆμ„ 것이닀.