// 참조 투명성 테스트 코드
def failingFn(i: Int): Int = {
val y: Int = throw new Exception("fail!")
try {
val x = 42 + 5
x + y
}
catch { case e: Exception => 43 }
}
def failingFn2(i: Int): Int = {
try {
val x = 42 + 5
x + ((throw new Exception("fail!")): Int)
}
catch { case e: Exception => 43 }
}
println(failingFn(12))
//println(failingFn2(12))
목표
Option
,Either
를 구현해보며 오류처리 방법 이해4.1 예외의 장단점
목록 4.1
https://scalafiddle.io/sf/YbyNapO/0
참조 투명성
예외의 주된 문제
4.2 예외의 가능한 대안들
대안1. 별도의 값 반환
NaN
,null
, ...대안2. 행동을 알려주는 인수 전달
onEmpty
만으로 유연성을 얻기 힘듬4.3 Option 자료 형식
4.3.1 Option의 사용 패턴
사용 예시
Map
에서 key 찾기Option에 대한 기본적인 함수를
List
와 비슷Option
은 최대 하나의 원소만 담을 수 있음trait
을 사용하여 구현해봄getOrElse
,orElse
B >: A
기본적인 Option 참수들의 용례
None
을 반환하여 나머지 호출 취소정리
4.3.2 예외 지향적 API의 Option 합성과 승급, 감싸기
Option
으로 온통 도배되지 않을지 우려?Option
에 대해 작용하는 함수로 승급(lift) 가능for-comprehension(함축)
{}
블럭 안에 묶음(binding) 표현yield
내에서 좌변의 값 사용 가능flatMap
으로 전개하고 마지막 묶음과yield
는map
호출로 변환한다.4.4 Either 자료 형식
Option
단점None
반환.Option
과의 차이4.5 요약
orElse
,getOrElse
,Try