Hanbit the Developer

Kotlin Documentation | Properties 본문

Kotlin

Kotlin Documentation | Properties

hanbikan 2023. 5. 22. 17:42

Kotlin Documentation 시리즈에 대해

Category: Concepts - Classes and objects

문서 링크: https://kotlinlang.org/docs/properties.html


Getters and setters

var <propertyName>[: <PropertyType>] [= <property_initializer>]
    [<getter>]
    [<setter>]
var stringRepresentation: String = "Init"
    get() = this.toString()
    set(value) {
        setDataFromString(value) // parses the string and assigns values to other properties
    }
  • setter의 visibility modifier 정의:
var setterVisibility: String = "abc"
    private set // the setter is private and has the default implementation

Backing properties

  • field에 값을 대입함으로써 실제 값을 변경한다:
var counter = 0 // the initializer assigns the backing field directly
    set(value) {
        if (value >= 0)
            field = value
            // counter = value // ERROR StackOverflow: Using actual name 'counter' would make setter recursive
    }

Compile-time constants

어떤 값이 컴파일 타임에 알 수 있고 read-only라면 constant를 사용하라.(compile time constant라고 부른다.)

그러한 프로퍼티는 다음과 같은 조건을 만족해야 한다:

  • Top-level property이거나 object 또는 companion object의 멤버이다.
  • String이나 primitive 타입의 값으로 초기화되어야 한다.
  • Custom getter가 될 수 없다.

이는 annotation에 사용될 수 있다.

const val SUBSYSTEM_DEPRECATED: String = "This subsystem is deprecated"

@Deprecated(SUBSYSTEM_DEPRECATED) fun foo() { ... }

*장점: 성능 최적화, 가독성 증가, 컴파일 타임 에러 발견(ChatGPT)

Lateinit

public class MyTest {
    lateinit var subject: TestSubject

    @SetUp fun setup() {
        subject = TestSubject()
    }

    @Test fun test() {
        subject.method()  // dereference directly
    }
}
  • 초기화 체크
if (foo::bar.isInitialized) {
    println(foo.bar)
}

Delegated properties

'Kotlin' 카테고리의 다른 글

Kotlin Documentation | Functional (SAM) interfaces  (0) 2023.05.22
Kotlin Documentation | Interfaces  (0) 2023.05.22
Kotlin Documentation | Inheritance  (0) 2023.05.22
Kotlin Documentation | Classes  (0) 2023.05.22
Kotlin Documentation | Reflection  (0) 2023.05.22