Home > Mobile >  what does XXX<U, in T: U> mean in kotlin
what does XXX<U, in T: U> mean in kotlin

Time:06-05

what does TimeoutCoroutine<U, in T: U> mean in kotlin. I was reading this

private class TimeoutCoroutine<U, in T: U>(
    @JvmField val time: Long,
    uCont: Continuation<U> // unintercepted continuation
) 

but really don't understand what this <U, in T> means. Could someone explain? thanks a lot!

CodePudding user response:

TimeoutCoroutine is a generic class who need two types :

  • U, it can be whatever you want

  • T who extends the U type directly or indirectly (defined by T: U)

  • the in keyword, According to the documentation

    It makes a type parameter contravariant, meaning it can only be consumed and never produced.

    So you will be able to use the T type but never create an instance of it or returning it in a method.

For exemple :

class Foo<in T> {
    fun bar(a: T) = a
}

the bar function will show you an error saying that this method use the T type with out position instead of in because you are returning an object who has the T type

  • Related