정구리의 우주정복

[Kotlin] findById().orElseThrow와 findById()의 차이 (Optional) 본문

JAVA/STUDY

[Kotlin] findById().orElseThrow와 findById()의 차이 (Optional)

Jungry_ 2025. 2. 18. 22:38
반응형

코드를 쓰다보면

 

val routine = routineRepository.findById(routineId).orElseThrow{ IllegalArgumentException("routine not found") }

 

이렇게 작성한 경우에는 routine 의 값을 가져올때 (isSuccess)

 

routine.isSuccess

 

이렇게 가져오고

 

val routine = routineRepository.findById(routineId)

 

요롷게 하면 

routine.get().isSuccess

 

이렇게 가져와야한다 왤까

 

바로바로 타입의 차이이다 

orElseThrow 를 사용하게 되면 값이 존재하면 객체 (Routine) 를 반환하고 없으면 예외를 발생하기 때문에 무조건 객체를 가지고 있다고 생각하기 때문에

routine.isSuccess 와 같이 접근할 수 있다.

 

findById() 는 Optional<Routine> 를 반환하므로 Optional 을 먼저 .get() 으로 풀어야 실제 객체를 꺼내서 쓸 수 있다

 

코드 / 반환 타입 /  isSuccess 접근 방식

findById(routineId).orElseThrow { ... } Routine routine.isSuccess
findById(routineId) Optional<Routine> routine.get().isSuccess

 

반응형
Comments