๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๋นˆ ๊ตฌ๋ฉ ์ฑ„์šฐ๊ธฐ

[Kotlin] Companion objects

kotlinlang.org/docs/object-declarations.html#companion-objects

 

Object expressions and declarations | Kotlin

 

kotlinlang.org

ํด๋ž˜์Šค ์•ˆ์˜ ์˜ค๋ธŒ์ ํŠธ ์„ ์–ธ์€ companion ํ‚ค์›Œ๋“œ๋กœ ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค.

class MyClass {
    companion object Factory {
        fun create(): MyClass = MyClass()
    }
}

companion object์˜ ๋ฉค๋ฒ„๋“ค์€ ๋‹จ์ˆœํ•˜๊ฒŒ ํด๋ž˜์Šค ์ด๋ฆ„์„ ํ•œ์ •์ž๋กœ ์‚ฌ์šฉํ•ด์„œ ํ˜ธ์ถœํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

val instance = MyClass.create()

companion object์˜ ์ด๋ฆ„์€ ์ƒ๋žต ๊ฐ€๋Šฅํ•œ๋ฐ, ์ด ๊ฒฝ์šฐ Companion ์ด๋ž€ ์ด๋ฆ„์ด ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

class MyClass {
    companion object { }
}

val x = MyClass.Companion

ํด๋ž˜์Šค์˜ ์ด๋ฆ„ ์ž์ฒด(๋‹ค๋ฅธ ์ด๋ฆ„์˜ ํ•œ์ •์ž๋กœ์„œ๊ฐ€ ์•„๋‹ˆ๋ผ)๋Š” ํด๋ž˜์Šค์˜ (์ด๋ฆ„ ์—ฌ๋ถ€์— ์ƒ๊ด€์—†์ด) companion object๋ฅผ ์ฐธ์กฐํ•ฉ๋‹ˆ๋‹ค.

class MyClass1 {
    companion object Named { }
}

val x = MyClass1

class MyClass2 {
    companion object { }
}

val y = MyClass2

companion object๋“ค์˜ ๋ฉค๋ฒ„๋“ค์ด ๋‹ค๋ฅธ ์–ธ์–ด๋“ค์˜ static ๋ฉค๋ฒ„๋กœ ๋ณด์ผ ์ˆ˜ ์žˆ๋”๋ผ๋„, ๋Ÿฐํƒ€์ž„์—์„œ ์ด ๋ฉค๋ฒ„๋“ค์€ ์ง„์งœ objects๋“ค์˜ ์ธ์Šคํ„ด์Šค ๋ฉค๋ฒ„๋“ค์ด๊ณ , interface๋ฅผ ๊ตฌํ˜„ํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.

interface Factory<T> {
    fun create(): T
}

class MyClass {
    companion object : Factory<MyClass> {
        override fun create(): MyClass = MyClass()
    }
}

val f: Factory<MyClass> = MyClass

๊ทธ๋Ÿฌ๋‚˜ JVM์—์„œ @JvmStatic ์ฃผ์„์„ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ, companion object๋“ค์€ ์ง„์งœ static ํ•จ์ˆ˜์™€ ํ•„๋“œ๋“ค๋กœ ์ƒ์„ฑ๋ฉ๋‹ˆ๋‹ค.

 

 

 

 

'๋นˆ ๊ตฌ๋ฉ ์ฑ„์šฐ๊ธฐ' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Kotlin] Companion Object์˜ ํ™œ์šฉ  (0) 2021.03.29
[Kotlin] Functional (SAM) interface  (0) 2021.03.29
[์šฉ์–ด] sideload  (0) 2021.03.26
[Kotlin] Sequence  (0) 2021.03.26
[Java] Daemon thread  (0) 2021.03.26