operator fun invoke(amount: BigDecimal, currency: Currency) =
Money(
amount.setScale(currency.defaultFractionDigits),
currency
)
이제는
Money
동반 객체를 함수처럼 호출하는 코드가 생성자 호출처럼 보인다. 그렇다면
invoke
메서드의
Money
(...)
호출이 스택 넘침
stack
overflow
을 일으키지 않는 이유는 무엇일
까?
invoke
메서드 안에서
Money
(...)
호출은
invoke
를 재귀 호출하지 않고 비공개
Money
생성자를 호출한다. 반면 클래스 밖에서는
Money
의 생성자를 볼 수 없으므로
Money
(...)
가
동반 객체의
invoke
를 호출한다. 우리는 두 세계의 장점, 즉 클래스 인스턴스 생성을 편리하게
할 수 있는 구문과 클래스의 불변 조건을 보장하는 캡슐화 경계를 동시에 취할 수 있다.
기존 코틀린 코드가 새 문법을 사용하려면 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.