https://kotlinlang.org logo
Title
c

ckchen

11/03/2018, 12:44 PM
I am learning coroutines and I got confused when I see the code
coroutineContext[Job]
. Isn’t
Job
an interface? Why can it be used for indexing? I have checked the source (
public operator fun <E : Element> get(key: Key<E>): E?
of
CoroutineContext
) and still don’t have a clue.
k

karelpeeters

11/03/2018, 12:49 PM
What happens when you do
Ctrl+B
on
Job
?
c

ckchen

11/03/2018, 12:50 PM
public interface Job : CoroutineContext.Element
I mean,
Job
is an interface, not an instance of
Key<E>
. Why can it be passed to
public operator fun <E : Element> get(key: Key<E>): E
?
k

karelpeeters

11/03/2018, 12:54 PM
Dammit I remember reading about this, I completely forgot though. You might have more luck asking in #coroutines
e

elizarov

11/03/2018, 12:57 PM
It is called companion object.
k

karelpeeters

11/03/2018, 1:01 PM
Huh might be misremembering then, wasn't there something special about
[Job]
?
c

ckchen

11/03/2018, 1:04 PM
I see this
public companion object Key : CoroutineContext.Key<Job>
in
Job
. So, why not
coroutineContext[Job.Key]
?
e

elizarov

11/03/2018, 1:05 PM
You can use
Job.Key
. But since
Key
is a companion object to
Job
, simply using
Job
works, too.
c

ckchen

11/03/2018, 1:06 PM
Is this a hidden secret? 😀 I don’t see it addressed in the document of companion objects.
k

karelpeeters

11/03/2018, 1:08 PM
They explain it the other way around, first with a custom name and then "you can omit it".
c

ckchen

11/03/2018, 1:11 PM
I know. But I thought they are talking about calling the method of the companion object. I didn’t expect that we can refer to the companion object by omitting it and just use the class name.
e

elizarov

11/03/2018, 3:31 PM
Indeed, it is not explicitly spelled in the docs. It would be nice to add such an example there
c

ckchen

11/04/2018, 12:52 AM
Yes. So I made a simple pull request yesterday (https://github.com/JetBrains/kotlin-web-site/pull/1192). Hope it would be helpful.