Hanbit the Developer
Kotlin Documentation | Classes 본문
Category: Concepts - Classes and objects
문서 링크: https://kotlinlang.org/docs/classes.html
Constructor
class Person constructor(firstName: String) { /*...*/ }
생성자에 어노테이션(e.g. class A @Inject constructor(…))이나 visibility modifiers가 없다면 constructor 키워드를 생략해도 된다:
class Person(firstName: String) { /*...*/ }
init
class InitOrderDemo(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}")
}
}
/*
First property: hello
First initializer block that prints hello
Second property: 5
Second initializer block that prints 5
*/
- Primary constructor
- constructor는 코드를 가질 수 없기 때문에 필요성이 대두되었다.
Trailing comma
class Person(
val name: String,
var age: Int, // trailing comma
) { /*...*/ }
With annotations or visibility modifiers
class Customer public @Inject constructor(name: String) { /*...*/ }
Secondary constructors
class Person(val name: String) {
val children: MutableList<Person> = mutableListOf()
constructor(name: String, parent: Person) : this(name) {
parent.children.add(this)
}
}
'Kotlin' 카테고리의 다른 글
Kotlin Documentation | Properties (0) | 2023.05.22 |
---|---|
Kotlin Documentation | Inheritance (0) | 2023.05.22 |
Kotlin Documentation | Reflection (0) | 2023.05.22 |
Kotlin Documentation | Destructuring declarations (1) | 2023.05.22 |
Kotlin Documentation | Annotations (0) | 2023.05.22 |