본문

170821(월) - Kotlin docs (Properties and Fields)

Kotlin docs


Properties and Fields


Declaring Properties

- class에서 mutable한 properties들 선언 가능

ㆍvar

ㆍval



Getters and Setters

- getter, setter는 option

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


- property가 infer 가능하다면 생략 가능

var allByDefault: Int? // error: explicit initializer required, default getter and setter implied var initialized = 1 // has type Int, default getter and setter


- read-only 는 setter가 허용되지 않음

val simple: Int? // has type Int, default getter, must be initialized in constructor val inferredType = 1 // has type Int and a default getter


- custom getter

val isEmpty: Boolean get() = this.size == 0


- custom setter

ㆍvalue는 다른이름 가능


var stringRepresentation: String get() = this.toString() set(value) { setDataFromString(value) // parses the string and assigns values to other properties }


- Kotlin 1.1 부터는 getter에서 infer 가능할 경우 property type 생략 가능

val isEmpty get() = this.size == 0 // has type Boolean


- body 변경 없이 accessor 나 annotation 변경가능

var setterVisibility: String = "abc" private set // the setter is private and has the default implementation var setterWithAnnotation: Any? = null @Inject set // annotate the setter with Inject


- Backing field

ㆍKotlin class에 field는 있을 수 없지만, custom accessor사용시 backing field가 필요하다.

ㆍfield 식별자를 사용하여 access 가능한 backing field 제공

var counter = 0 // the initializer value is written directly to the backing field set(value) { if (value >= 0) field = value }


ㆍproperty의 accessor에서만 사용 가능

ㆍaccessor중 하나 이상의 default implemetation을 사용하거나 custom accessor가 field 식별자를 통해 이를 참조하는 경우 backing field 생성

ㆍ다음의 경우 backing field가 없음

val isEmpty: Boolean get() = this.size == 0


- backing properties

ㆍ implicit 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") }



Compile-time constants

ㆍcompile-time에 value가 알려진 property는 const modifier를 사용해서 constants로 표시될 수 있다.

ㆍ요구사항

- top level 또는 object의 member

- String 또는 primitive type으로 initalized 

- no custom getter


const val SUBSYSTEM_DEPRECATED: String = "This subsystem is deprecated" @Deprecated(SUBSYSTEM_DEPRECATED) fun foo() { ... }



Late-Initialized Properties

ㆍInjection 및 unit test시에 property 초기화는 굉장히 불편하다.

ㆍconstructor에서 null이 아닌 initalizer를 제공할 수 없지만 class 내부에서 null 검사를 피하려고 한다.


public class MyTest { lateinit var subject: TestSubject @SetUp fun setup() { subject = TestSubject() } @Test fun test() { subject.method() // dereference directly } }


ㆍvar property에서만 사용 가능

ㆍprimary constructor에서 사용 불가

ㆍproperty에 custom getter, setter가 없어야 한다.

ㆍproperty는 non-null이어야 한다.

ㆍprimitive type이 아니어야 한다.

ㆍ초기화 되기전에 property에 access하면 Exception throw



Overriding properties

See Overriding Properties



Delegated properties

delegated properties.

공유

댓글

고뇌하는 식빵남아

design by tokiidesu. powerd by AXZ.