by 키워드를 사용하여 위임하기
위임의 여러 가지 방법
- 클래스 위임
- Class를 선언할 때
by
키워드를 사용하여 위임할 수 있다. - 구현되지 않은 내용만 위임 객체에 의해 구현된다.
- 위임 객체는 내부적으로 필드로 선언되어 사용된다.
interface ExampleInterface { fun exampleMethod() } class Delegator(delegatee: ExampleInterface): ExampleInterface by delegatee // 내부적으로 위임 객체를 저장할 필드가 선언된다. 실제 구현은 해당 필드를 통해 이루어진다. fun main() { val exampleInterfaceImpl = object: ExampleInterface { override fun exampleMethod() { println("Example method executed.") } } val delegator = Delegator(exampleInterfaceImpl) delegator.exampleMethod() // "Example method executed."가 출력된다. }
- Class를 선언할 때
- 프로퍼티 위임
- 필드를 선언할 때
by
키워드를 사용하여 위임할 수 있다. - 필드에 접근하는 방식을 제어한다.
- 필드를 선언할 때
- 기타