Study Record

[Kotlin] property 본문

안드로이드/Kotlin

[Kotlin] property

초코초코초코 2023. 7. 21. 01:08
728x90

Property 선언하기

 

코틀린 클래스에서 Property는 var, val 키워드를 사용하여 선언할 수 있다. val 키워드가 붙으면 읽기만 가능하며 var 키워드가 붙으면 수정가능하다.

class Address {
    var name: String = "Holmes, Sherlock"
    var street: String = "Baker"
    var city: String = "London"
    var state: String? = null
    var zip: String = "123456"
}

 

 

Getters and Setter

 

Property 에 Getter와 Setter를 선언할 수 있다. 선택적이기 때문에 반드시 구현할 필요는 없다. 구현하지 않으면 자동으로 Kotlin이 기본 Getter와 Setter를 선언해 준다. 

var <propertyName>[: <PropertyType>] [= <property_initializer>]
    [<getter>]
    [<setter>]

var 키워드가 붙은 property 는값을 수정하는 것이 가능하기 때문에 Getter와 Setter 모두 구현할 수 있지만 val 키워드가 붙으면 수정 불가능하다. 따라서 val 키워드가 붙은 property는 Getter 만 가능하다.

 

class Rectangle(val width: Int, val height: Int) {
    val area: Int // property type is optional since it can be inferred from the getter's return type
        get() = this.width * this.height
}

PropertyType 은 생략 가능하다. 따라서 다음과 같이 선언할 수 있다.

val area get() = this.width * this.height

 

 

Backing fields

코틀린에서 field 는 메모리에 존재하는 property의 실제 값(value)을 유지하기 위해 속성의 일부로만 사용된다. field를 직접 선언할 수 없지만 property에서 Backing field 가 필요할 때가 있는데 그때 자동으로 "field" 키워드로 접근자(Getter And Setter)에 한해서 사용할 수 있다.

 

Backing fields 가 필요할 때는 다음과 같이 Setter 를 통해 property 값을 수정할 때 이름 그대로 "count = value"를 실행하면 재귀 호출로 에러가 난다.

class Child {
    var count = 0
        set(value) {
            count = value
        }
}

코드를 그대로 JAVA Decompile 시키면 setCount() 함수의 내용에 다시 setCount() 를 부르고 있다. 이렇게 재귀 호출이 반복되어 에러가 난다.

public final class Child {
   private int count;

   public final int getCount() {
      return this.count;
   }

   public final void setCount(int value) {
      this.setCount(value);
   }
}

 

이때 사용가능한 것이 Backing field이다. "field" 키워드를 사용하여 count 대신 field를 넣는다.

class Child {
    var count = 0
        get() = field
        set(value) {
            field = value
        }
}

이 코드를 그대로 JAVA Decompile 시키면 재귀 호출의 위험이 사라진다.

public final class Child {
   private int count;

   public final int getCount() {
      return this.count;
   }

   public final void setCount(int value) {
      this.count = value;
   }
}

 

 

Backing Properties

Backing Field 스키마를 사용하지 않고 Backing Property 를 만들 수 있다.

private var _table: Map<String, Int>? = null
public val table: Map<String, Int>
    get() {
        if (_table == null) {
            _table = HashMap() // Type parameters are inferred
        }
        return _table ?: throw AssertionError("Set to null by another thread")
    }

 

 

lateinit 키워드

null 이 아닌 property 의 초기화를 lateinit 키워드를 사용하여 늦출 수 있다. 단, 반드시 lateinit 키워드가 선언된 property 라면 사용되기 전에 초기화되어야 하며 Getter와 Setter가 따로 정의되어있지 않아야 한다.

public class MyTest {
    lateinit var subject: TestSubject
    /**/
}

 

 

 

 

Properties | Kotlin

 

kotlinlang.org

 

728x90

'안드로이드 > Kotlin' 카테고리의 다른 글

[Kotlin] Exception Class (예외 처리)  (0) 2023.08.09
[Kotlin] coroutines 살펴보기  (0) 2023.08.08
[Kotlin] object  (0) 2023.07.20
[Kotlin] 람다식 및 고차함수  (0) 2023.07.19
[Kotlin] vararg 키워드  (0) 2023.07.17