-
5-3. 고급 함수와 함수형 프로그래밍 활용하기 : 확장 프로퍼티Study(종료)/Kotlin 22.09.13 ~ 12.18 2022. 10. 8. 23:42
5장
5-1. 고급 함수와 함수형 프로그래밍 활용하기 : 코틀린을 활용한 함수형 프로그래밍5-2. 고급 함수와 함수형 프로그래밍 활용하기 : 확장5-3. 고급 함수와 함수형 프로그래밍 활용하기 : 확장 프로퍼티
5-4. 고급 함수와 함수형 프로그래밍 활용하기 : 동반 확장
5-5. 고급 함수와 함수형 프로그래밍 활용하기: 수신 객체가 있는 호출 가능 참조
5-3. 확장 프로퍼티
1) 확장 프로퍼티
앞에서 사용했던 확장 함수와 비슷하게 확장 프로퍼티 역시 정의할 수 있다.
다른 일반 멤버 프로퍼티와 동일한 방법으로 확장 프로퍼티에 접근할 수 있으며 문법도 비슷하다.
val IntRange.leftHalf: IntRange get() = start..(start + endInclusive)/2 fun main() { println((11..33).leftHalf) // 11..22 println((33..66).leftHalf) // 33..49 }
멤버 프로퍼티와 확장 프로퍼티의 가장 큰 차이는 어떤 클래스의 인스턴스에 안정적으로 상태를 추가할 방법이 없기 때문에backing-field를 쓸 수 없다는 점이다. 즉 확장 프로퍼티를 초기화할 수 없으며 접근자 안에서 field를 사용할 수도 없고,lateinit을 이용해 확장 프로퍼티를 정의할 수 없다(lateinit은 backing-field에 의존하는 기능이므로)
위와 같은 이유로 확장 프로퍼티 정의에서는 항상 명시적인 게터를 정의해야 하고,
가변 프로퍼티의 경우 세터도 명시해야 한다.
val IntArray.midIndex get() = lastIndex/2 var IntArray.midValue get() = this[midIndex] set(value){ this[midIndex] = value } fun main() { val numbers = IntArray(6) {it * it * it} // 0, 1, 8, 27, 64, 125 println(numbers.midValue) // 8 numbers.midValue *= numbers.midValue // 8 * 8 println(numbers.midValue) // 64 }
다음글
반응형'Study(종료) > Kotlin 22.09.13 ~ 12.18' 카테고리의 다른 글
5-5. 고급 함수와 함수형 프로그래밍 활용하기 : 수신 객체가 있는 호출 가능 참조 (0) 2022.10.10 5-4. 고급 함수와 함수형 프로그래밍 활용하기 : 동반 확장 (0) 2022.10.09 5-2. 고급 함수와 함수형 프로그래밍 활용하기 : 확장 (0) 2022.10.08 5-1. 고급 함수와 함수형 프로그래밍 활용하기 : 코틀린을 활용한 함수형 프로그래밍 (0) 2022.10.08 4-4. 클래스와 객체 다루기 : 객체 (0) 2022.10.01