Singleton in Kotlin

CaChiJ·2022년 6월 26일
0

OOP in Kotlin

목록 보기
1/1

1. object

kotlin에는 object 표현식이 있다. object 표현식은 익명 클래스의 객체를 생성한다. 일반적으로 다음과 같이 사용된다.

fun main() {
    val helloWorld = object {
        val hello = "Hello"
        val world = "World"
        // object expressions extend Any, so `override` is required on `toString()`
        override fun toString() = "$hello $world"
    }
    print(helloWorld)
}

싱글톤 클래스 객체로 사용할 때는 다음과 같이 사용한다.

object SomeSingleton {
    init {
        println("init complete")
    }
}

클래스가 명시적으로 선언되어 있지 않기 때문에 같은 객체를 새롭게 생성할 수 없다. object는 처음으로 접근될 때 lazy하게 생성된다. 이는 내부적으로는 java의 static initialization block을 이용한다. 덕분에 double-checked locking과 같은 복잡한 코드없이 thread-safe하게 singleton을 구현할 수 있다.

2. companion

object를 이용한 구현의 문제점은 객체를 생성할 때 인자를 전달할 수 없다는 점이다. 만약 인자를 전달하고 싶은 경우에는 companion을 사용하면 된다.

companion object {
    val instance = UtilProject()
} 

companion으로 생성된 객체는 외부에서 접근할 때 마치 static 멤버처럼 동작한다. 하지만 내부적으로는 일반적인 인스턴스 객체와 같다.

Reference

Christophe Beyls : Kotlin singletons with argument
Kotlinlang.org : Object expressions and declarations
Kotlinlang.org : Companion objects

0개의 댓글