728x90
반응형
1. sealed 클래스
sealed 클래스는 자신의 중첩 클래스에만 상속을 허용하는 클래스이다.
// Outer 클래스는 자신의 중첩 또는 내부 클래스에서만 상속이 가능하다. Outer 클래스 자체로는 인스턴스 생성 불가능
sealed class Outer {
class One: Outer()
class Two: Outer()
class Three: Outer()
}
// Outer 클래스는 자신의 중첩 클래스에서만 상속이 가능하기 때문에 주석을 해제하면 오류 발생
// class Four: Outer()
fun main() {
val instance:Outer = Outer.Three()
val test: Outer
/*
sealed 클래스는 서브클래스가 sealed 클래스 안에 모두 존재하므로,
모든 서브 타입을 체크했다면 when의 else 블록을 생략해도 표현식을 구성할 수 잇다.
*/
val text: String = when(instance) {
is Outer.One -> "첫 번째"
is Outer.Two -> "두 번째"
is Outer.Three -> "세 번째"
}
println(text) // 세 번째
}
코틀린 1.1 버전 이후에는 sealed 클래스와 같은 파일에 속해 있기만해도 sealed 클래스를 상속할 수 있다.
2. 위임된 프로퍼티(Delegated Property)
프로그램을 작성하다 보면 Int 타입의 프로퍼티에 음수가 저장되는 것을 방지하는 Setter를 정의할 때가 자주 있다.
이렇게 모든 프로퍼티의 Setter를 일일이 정의하는 것은 너무 번거롭기에 코틀린에서는 이런 상황을 위해 프로퍼티의 Getter/Setter 구현을 다른 객체에 맡길 수 있는 문법을 제공한다.
프로퍼티 선언문 뒤에 by 객체를 적으면 해당 객체가 프로퍼티의 Getter/Setter를 대리하게 된다.
class Sample {
var number: Int by OnlyPositive()
}
프로퍼티를 대리하는 객체는 operator fun getValue(thisRef: Any?, property: KProperty<*>): T 와
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) 멤버 함수를 갖고 있어야 한다.
여기서 T는 대리할 프로퍼티의 타입이다.
Sample 클래스의 number 프로퍼티의 Getter는 OnlyPositive의 getValue로 대체, Setter는 setValue로 대체된다.
class OnlyPositive {
private var realValue: Int = 0
operator fun getValue(thisRef: Any?, property: KProperty<*>): Int {
return realValue
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) {
realValue = if(value > 0 ) value else 0
}
}
fun main() {
val sample = Sample()
sample.number = -50
println(sample.number) // 0
sample.number = 100
println(sample.number) // 100
}
3. 클래스 위임(Class Delegation)
코틀린에서는 인터페이스의 구현을 다른 클래스에 맡길 수 있는 문법도 제공한다.
// Int 타입과 덧셈을 가능하게 하는 인터페이스 선언
interface Plusable {
operator fun plus(other: Int): Int
}
// Plusable 인터페이스를 구현
class ClassDelegator: Plusable {
override fun plus(other: Int): Int {
println("기본 구현")
return other
}
}
인터페이스를 구현하면서 뒤에 by 객체를 지정하면 인터페이스의 구현을 해당 객체로 위임한다.
이 때 객체는 대리할 인터페이스를 구현하고 있어야 한다.
class Sample: Plusable by ClassDelegator()
fun main() {
// Sample의 plus 연산자 멤버 함수를 호출하면 ClassDelegator의 plus가 호출됨
println(Sample() + 10)
/*
기본 구현
10
*/
}
728x90
반응형
'TIL > Kotlin' 카테고리의 다른 글
[TIL/Kotlin] Kotlin, SpringBoot, JPA nativeQuery 사용시 주의사항 (0) | 2023.12.05 |
---|---|
[TIL/Kotlin] 우체국 Open API로 EMS 배송 추적하기 (0) | 2023.10.15 |
[TIL/Kotlin] 코틀린 고급문법_열거 클래스(Enum Class)와 열거 클래스에 프로퍼티와 멤버 함수 선언 및 활용하기 (0) | 2023.05.27 |
[TIL/Kotlin] 코틀린 고급문법_배열(Array)과 배열을 가변 인수로 활용하기 (0) | 2023.05.26 |
[TIL/Kotlin] 코틀린 고급문법_반복자(Iterator)와 반복문 for문 (0) | 2023.05.26 |