Kotlin

[Kotlin] 코틀린의 클래스(Class), 생성자(Constructor), 초기화 블록(Initializer blocks), 인스턴스(Instance) 사용법

yujinius 2024. 7. 22. 16:54

💗 클래스 Classes

  • Kotlin에서 클래스들은 class 키워드로 선언
  • class Person { /*...*/}
  • 클래스 선언은 클래스 이름, 클래스 헤더(타입 매개변수, 기본 생성자 등 지정) 및 중괄호로 둘러싸인 클래스 본문으로 구성
  • 헤더와 본문은 선택 사항이며, 클래스에 본문이 없으면 중괄호를 생략할 수 있음
  • class Empty

💗 생성자 Constructors

  • Kotlin의 클래스에는 기본 생성자(primary constructor)와 하나 이상의 보조 생성자(secondary constructors)가 있을 수 있음
  • 기본 생성자는 클래스 헤더에 선언되며, 클래스 이름과 선택적 타입 매개변수 뒤에 온다.
  • class Person constructor(firstName: String) { /*...*/ }
  • 기본 생성자에 annotaionsvisibility modifier 가 없으면 constructor 키워드를 생략할 수 있음
  • class Person(firstName: String) { /*...*/ }

기본 생성자가 하는 일

  • 기본 생성자는 클래스 인스턴스와 클래스 헤더에 있는 속성을 초기화
  • 클래스 헤더에는 실행 가능한 코드를 포함할 수 없음

initializer blocks

  • 객체 생성 중에 코드를 실행하려면 클래스 본문 내에서 initializer blocks을 사용
  • 이니셜라이저 블록은 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}") } }

initializer blocks 사용하는 이유

  1. 기본 생성자 매개변수는 initalizer blocks에서 사용 가능 ⇒ 추가 작업 가능
  2. 클래스 본문에 선언된 속성 초기화에 사용
  • 기본 생성자 매개변수는 이니셜라이저 블록에서 사용할 수도 있고, 클래스 본문에 선언된 속성 초기화에서 사용할 수도 있음
  • class Customer(name: String) { val customerKey = name.uppercase() }
  • Kotlin은 기본 생성자에서 속성을 선언하고 초기화하는 간결한 구문을 가지고 있음
  • class Person(val firstName: String, val lastName: String, var age: Int)
  • 이러한 선언에는 클래스 속성의 기본값도 포함될 수 있음
  • class Person(val firstName: String, val lastName: String, var isEmployed: Boolean = true)
  • 클래스 속성을 선언할 때 후행 쉼표(trailing comma)를 사용 가능
  • class Person( val firstName: String, val lastName: String, var age: Int, // trailing comma ) { /*...*/ }
  • 일반 속성과 마찬가지로, 기본 생성자에서 선언된 속성은 가변(var) 또는 읽기 전용(val)일 수 있음
  • 생성자에 어노테이션이나 가시성 수정자가 있는 경우 constructor 키워드가 필요하며 수정자는 생성자 키워드 앞에 온다.
  • class Customer public @Inject constructor(name: String) { /*...*/ }

 

💫 보조 생성자 Secondary constructors

  • 클래스는 보조 생성자를 선언할 수 있으며, 이는 constructor 키워드로 시작
  • class Person(val pets: MutableList<Pet> = mutableListOf()) class Pet { constructor(owner: Person) { owner.pets.add(this) // adds this pet to the list of its owner's pets } }
  • 클래스에 기본 생성자가 있는 경우 각 보조 생성자는 기본 생성자에게 직접 또는 다른 보조 생성자를 통해 간접적으로 위임해야 함
  • 동일 클래스의 다른 생성자에게 위임하려면 this 키워드를 사용
  • class Person(val name: String) { val children: MutableList<Person> = mutableListOf() constructor(name: String, parent: Person) : this(name) { parent.children.add(this) } }

⁉️ 보조 생성자에서의 initalizer blocks 실행 타이밍은 언제일까? 
https://yujinius45.tistory.com/97

 

[Kotlin] 보조 생성자(secondary constructors)에서의 초기화 블록(initializer blocks) 실행 타이밍

보조 생성자(Secondary constructors)에서 초기화 블록(initializer blocks) 실행 타이밍은 언제일까? 정답은 일단 보조 생성자 첫 문장 접근 순간! 이다. 이제 왜 그런건지 차근차근 알아보자.이니셜라이저

yujinius45.tistory.com

 

💗 클래스 인스턴스 생성 Creating instances of classes

  • 클래스 인스턴스를 생성하려면 생성자를 일반 함수처럼 호출
  • 생성된 인스턴스를 변수에 할당할 수 있음
val invoice = Invoice()

val customer = Customer("Joe Smith")

💗 클래스 멤버 Class members


kotlin 공식 docs 참고

https://kotlinlang.org/docs/classes.html

 

Classes | Kotlin

 

kotlinlang.org