Kotlin Companion Object 이름 생략
Published in
2 min readOct 9, 2019
kotlin coroutine context 를 살펴보다 보면, 아래와 같은 Job 이라는 객체를 coroutineContext 에서 get 으로 가져오는 경우를 종종 볼 수 있다.
- get은 아래와 같이 정의되어 있고
public operator fun <E : Element> get(key: Key<E>): E?
- Key는 다음과 같은 정의를 가지고 있다
public interface Key<E : Element>
get 의 인자는 Key를 구현한 instance 가 와야하는데, Job은 ?
- Job에 static 형태로 접근할 수 있는 object 는 Key 뿐이다.
public interface Job : CoroutineContext.Element {
/**
* Key for [Job] instance in the coroutine context.
*/
public companion object Key : CoroutineContext.Key<Job> {
...
}
Kotlin companion object 문서를 보면 아래와 같은 예제가 있고
class MyClass1 {
companion object Named { }
}val x = MyClass1class MyClass2 {
companion object { }
}val y = MyClass2
다음과 같은 설명이 있다.
The name of a class used by itself (not as a qualifier to another name) acts as a reference to the companion object of the class (whether named or not):
즉, class name은 named 이건 아니건 companion reference 로 사용할 수 있다.
따라서, Job.Key 는 named 이기 때문에
coroutineContext[Job]
coroutineContext[Job.Key]
Job 과 Job.Key 는 동일한 instance 를 가리킨다.