Kotlin 다중 생성자 이해
이 기사는 원래 2022년 7월 23일 vtsen.hashnode.dev에 게시되었습니다.
Kotlin에는 하나의 기본 생성자와 많은 보조 생성자가 있습니다.
기본 생성자
매개변수가 하나인 기본 생성자입니다.
class Example constructor(private val param1: String) {
init {
println("init is called.")
}
}
constructor
키워드를 생략할 수도 있습니다.class Example(private val param1: String) {
init {
println("init is called.")
}
}
기본 생성자에서 초기화할 수 없습니다. 대신
init{}
블록에서 코드를 초기화해야 합니다.보조 생성자
아래에는 2개의 보조 생성자가 있습니다.
class Example(private val param1: String) {
init {
println("init is called.")
}
//First secondary constructor
constructor(
param1: String,
param2: String) : this(param1) {
println("Second constructor is called")
}
//Second secondary constructor
constructor(
param1: String,
param2: String,
param3: String) : this(param1) {
println("Third constructor is called")
}
}
여기에 몇 가지 중요한 참고 사항이 있습니다.
this(param1)
호출). 설마! 다음 섹션 참조 - Call Another Secondary Constructorvar
또는 val
를 선언할 수 있습니다.init{}
블록과 함께 기본 생성자는 보조 생성자 초기화 전에 먼저 호출됩니다.따라서 세 번째 생성자를 호출하면
val obj = Example(param1="1", param2="2", param3="3")
출력은 다음과 같습니다.
init is called.
Third constructor is called
다른 보조 생성자 호출
보조 생성자에서 기본 생성자를 호출하는 대신 다른 보조 생성자를 호출할 수도 있습니다.
이 예제에서 두 번째 보조 생성자는 첫 번째 보조 생성자를 호출합니다.
class Example(private val param1: String) {
init {
println("init is called.")
}
//First secondary constructor
constructor(
param1: String,
param2: String) : this(param1) {
println("Second constructor is called")
}
//Second secondary constructor
constructor(
param1: String,
param2: String,
param3: String) : this(param1, param2) {
println("Third constructor is called")
}
}
세 번째 생성자를 호출하면 출력은 다음과 같습니다.
init is called.
Second constructor is called
Third constructor is called
빈 기본 생성자
이것은 빈 기본 생성자와 보조 생성자 예제입니다.
class Example() {
init {
println("init is called.")
}
constructor(param1: String): this() {
println("Second constructor is called")
}
}
그러나 실제로 보조 생성자에서
this()
를 호출할 필요는 없습니다. 또한 Example()
를 Example
로 변경해야 합니다.class Example {
init {
println("init is called.")
}
constructor(param1: String) {
println("Second constructor is called")
}
}
보조 생성자 사용 사례
내 보기 모델에 Hilt 종속성을 주입하려고 할 때 보조 생성자를 사용해야 하는 필요성에 직면했습니다.
%[ https://vtsen.hashnode.dev/convert-view-model-to-use-hilt-dependency-injection ]
preview
매개변수가 @preview
jetpack 작성에 사용되는 이와 같은 코드가 있습니다. true
에서만 @preview
로 설정됩니다. 그러나 이 변경 사항을 포팅하여 종속성 주입Hilt
을 사용하면 이 종속성을 주입하지 못합니다.class MainViewModel(
private val repository: ArticlesRepository,
preview: Boolean = false,
) : ViewModel() {
/*...*/
}
따라서 이것을 아래의 보조 생성자로 나눕니다.
class MainViewModel(
private val repository: ArticlesRepository) : ViewModel() {
constructor (
repository: ArticlesRepository,
preview: Boolean) : this(repository) {
/*...*/
}
}
그래서 기본 생성자로
@Inject constructor
을 사용하고 @preview
에 보조 생성자를 사용합니다.Hilt
구현을 사용하면 다음과 같습니다.@HiltViewModel
class MainViewModel
@Inject constructor(
private val repository: ArticlesRepository,
) : ViewModel() {
constructor (
repository: ArticlesRepository,
preview: Boolean) : this(repository) {
/*...*/
}
/*...*/
}
결론
여러 생성자를 많이 사용하지 않았습니까? 그래서 나중에 참조할 수 있도록 여기에 문서화했습니다.
또한보십시오
Reference
이 문제에 관하여(Kotlin 다중 생성자 이해), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/vtsen/understand-kotlin-multiple-constructors-2hk5텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)