API Note:
Optional is primarily intended for use as a method return type
where there is a clear need to represent "no result," and
where using null is likely to cause errors.
A variable whose type is Optional should never itself be null;
it should always point to an Optional instance.
메소드가 반환할 결과 값이 '없음'을 명백하게 표현할 필요가 있고,
null 을 반환하면 에러가 발생할 가능성이 높은 상황에서 메소드의 반환 타입으로
Optional 을 사용하자는 것이 Optional 을 만든 주된 목적이다.
Optional 타입의 변수의 값은 절대 null 이어서는 안 되며,
항상 Optional 인스턴스를 가리켜야 한다.
import static org.junit.jupiter.api.Assertions.assertTrue;
@SpringBootTest
class Basic1ApplicationTests {
@Autowired
private QuestionRepository questionRepository;
@Test
void contextLoads() {
Optional<Question> oq = this.questionRepository.findById(1);
assertTrue(oq.isPresent());
Question q = oq.get();
q.setSubject("수정된 제목");
this.questionRepository.save(q);
}
}
1) Optional 객체 생성
Optional<Question> oq = this.questionRepository.findById(1);
2) Optional 객체 접근
if(oq.isPresent()){
return oq.get();
}else{
return oq.orElse(null);
}
String isNull;
String name;
isNull = "loose";
name = Optional.ofNullable(isNull).orElse("test");
System.out.println(name); //isNull값이 null이 아니므로 "loose" 출력
isNull = null;
name = Optional.ofNullable(isNull).orElse("test");
System.out.println(name); //isNull값이 null이므로 "test" 출력