Class
Kotlin은 Java와 마찬가지로 class 를 가지고 있고, class keyword를 통해 선언한다.
class Study { ... }
class는 class name, header, body로 구성되어 있고, 중괄호 {} 로 둘러 쌓여있다. 단, 만약 optional인 header와 body 중 body가 없을 경우 중괄호 {} 를 다음과 같이 생략해도 된다.
class Study
생성자(Constructors)
Kotlin의 class는 primary constructor, secondary constructor를 가질 수 있고, primary constructor는 최대 하나, secondary constructor는 복수개로 가질 수 있다.
Primary constructor
먼저 primary constructor는 class header의 일부로 class name 뒤에 선언한다.
class Study constructor(majorName: String) { ... }
만약 primary constructor 가 annotation이나 visibility modifier를 가지지 않는다면 constructor keyword는 생략할 수 있다.
class Study(majorName: String) { ... }
기본적으로 primary constructor는 class header에 선언만 존재하고, 자체 code를 가지지는 않는다. 대신 init keyword 로 표시되는 initializer block 내에 code를 별도로 표기한다. instance 초기화 과정에서 initializer block이 순차적으로 수행된다.
class Study(name: String) {
val firstProperty = "First property: $name".also(::println)
init {
println("First initializer block that prints ${name}")
}
val secondProperty = "Second property: ${name.length}".also(::println)
init {
println("Second initializer block that prints ${name.length}")
}
}
class header에 선언된 primary constructor의 parameter들은 initializer block 내 뿐만 아니라 property 초기화에서도 사용이 가능하다.
class Study(name: String) {
val majorKey = name.toUpperCase()
}
Secondary constructor
class는 primary constructor외에도 constructor keyword를 이용해 secondary constructor를 선언할 수 있다.
class Person {
constructor(parent: Person) {
parent.children.add(this)
}
}
secondary constructor는 this keyword를 통해 직간접적으로 primary constructor를 포함한 다른 secondary constructor들을 호출할 수 있다.
class Person(val name: String) {
constructor(name: String, parent: Person) : this(name) {
parent.children.add(this)
}
}
그리고 다음과 같이 initializer block 이 선언되어 있을 경우 secondary constructor body 수행 전에 일괄적으로 수행된다.
class Constructors {
init {
println("Init block")
}
constructor(i: Int) {
println("Constructor")
}
}
'Language > Kotlin' 카테고리의 다른 글
| Kotlin - for/while Loops (0) | 2018.07.24 |
|---|---|
| Kotlin - when expression (0) | 2018.07.23 |
| Kotlin - if expression (0) | 2018.07.17 |
| Kotlin - Control Flow (제어 흐름) (0) | 2018.07.17 |
| Kotlin - Kotlin on Android (Android Studio for Windows) (0) | 2018.07.16 |
| Kotlin - Packages (0) | 2018.07.16 |
| Kotlin - Kotlin on JVM (the IntelliJ IDEA Community Edition for Windows) (0) | 2018.07.12 |
| Kotlin - Strings (문자열) (0) | 2018.07.11 |