Declaring properties - 프로퍼티 선언
코틀린 클래스의 속성은
var
키워드로 가변으로 선언 될 수도 있고 val
키워드로 read-only 로 설정 될 수 도 있다.class Address { var name: String = "Holmes, Sherlock" var street: String = "Baker" var city: String = "London" var state: String? = null var zip: String = "123456" }
속성을 사용하기 위해서는 그냥 참조하면 된다.
fun copyAddress(address: Address): Address { val result = Address() result.name = address.name // accessors are called result.street = address.street result.city = address.city result.state = address.state result.zip = address.zip return result }
Getters and setters
가변 속성 정의의 full syntax 는 아래와 같다.
var <propertyName>[: <PropertyType>] [= <property_initializer>] [<getter>] [<setter>]
- initializer, getter, setter 는 옵션임
- 속성의 타입은 initializer 혹은 getter 의 리턴타입에서 타입 추론이 가능하다면 안 써도 됨
var initialized = 1 // has type Int, default getter and setter // var allByDefault // ERROR: explicit initializer required, default getter and setter implied
불변 속성의 선언 문법은 가변 속성과 두가지가 다르다
val
로 시작함
setter
없음
val simple: Int? // has type Int, default getter, must be initialized in constructor val inferredType = 1 // has type Int and a default getter
getter 와 setter 를 명시적으로 작성함으로써 커스텀한 접근자를 가질 수 있다.
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 }
var stringRepresentation: String get() = this.toString() set(value) { setDataFromString(value) // parses the string and assigns values to other properties }
컨벤션으로 세터의 인자 이름은는
value
를 사용한다.기본 게터와 세터를 사용하면서 게터와 세터의 가시성을 변경하고 싶을 때는 바디를 적지 않아도 된다.
var setterVisibility: String = "abc" private set // the setter is private and has the default implementation
Backing fields

backing field 는 접근자 (getter. setter)에서 사용 가능하며
field
identifier 를 사용한다.Backing properties
implicit 한 backing field schema 로 부족하다면 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") }