다음과 같이 Worker와 Student에 대한 interface가 있다고 할 때,
interface Worker { fun work() } interface Student { fun study() }
이 두 interface를 상속받는 클래스를 구현할 때는 다음과 같이 직접 상속받아 구현하는 방식을 주로 사용할 것이다.
class Developer : Worker, Student { override fun work() { println("Work hard!") } override fun study() { println("Study hard!") } }
Kotlin 에서는 by 키워드를 사용하면 interface를 상속하되 직접 구현하지 않고,
클래스의 프로퍼티에 해당 interface에 대한 역할을 위임(delegation)할 수 있다.
텍스트로만 설명하면 어렵지만 코드를 통해 보면 어떤 기능을 하는지 쉽게 파악할 수 있다.
class OfficeWorker : Worker { override fun work() { println("Work in my office") } } class WorkerStudent : Student { override fun study() { println("Study after work") } } class Developer( private val worker: Worker, private val student: Student ) : Worker by worker, Student by student fun main() { val developer = Developer(OfficeWorker(), WorkerStudent()) developer.work() developer.study() }
위 코드에서 보듯 Developer class는 Worker와 Student interface를 상속받지만 Developer class가 상속받는 interface 들을 직접 구현하지 않고,
worker, student 프로퍼티로 Worker와 Student의 역할을 위임하여 Worker와 Student의 역할을 수행할 수 있다.
처음 by 구문을 보면 어렵지만 막상 내용을 보면 매우 단순하다.
위 코드를 Java 코드로 decompile 하면 아래와 같이 되는 것을 확인할 수 있다.
자바 코드로는 몇 줄 더 추가해야할 것들이 Kotlin의 문법 덕분에 보다 간결하게 처리할 수 있다.
public final class Developer implements Worker, Student { private final Worker worker; private final Student student; public Developer(@NotNull Worker worker, @NotNull Student student) { Intrinsics.checkNotNullParameter(worker, "worker"); Intrinsics.checkNotNullParameter(student, "student"); super(); this.worker = worker; this.student = student; } public void work() { this.worker.work(); } public void study() { this.student.study(); } }
'Java & Kotlin > Kotlin' 카테고리의 다른 글
[MockK] 인자 값 그대로 리턴하기 (0) | 2022.04.14 |
---|---|
observable, vetoable를 통한 프로퍼티 변경 감지 (0) | 2021.11.06 |
by lazy를 통해 지연 초기화 적용하기 (0) | 2021.11.06 |
Kotlin Gradle Multi Module 적용하기 (0) | 2021.11.04 |
JUnit5 테스트 시 @BeforeEach, @AfterEach가 실행되지 않을 때 (0) | 2021.01.10 |
댓글