https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Jiri Bruchanov

07/19/2022, 3:35 PM
anyone who would be able to help ? I think I have lost type safety using inline function with reified type, but not sure why
having following code
Copy code
import kotlin.reflect.KClass

interface NavArgs
interface LifecycleComponent
interface NavToken<T : NavArgs>

class NavRecord<T : NavArgs, LC : LifecycleComponent>(
    val navToken: NavToken<T>,
    val klass: KClass<out LC>,
    val content: (LC) -> Unit
) {
    fun execute(lc: LC) {
        content(lc)
    }
}

inline fun <reified LC : LifecycleComponent, T : NavArgs> screen(
    navToken: NavToken<T>,
    noinline content: (LC) -> Unit
): NavRecord<T, LC> = NavRecord(navToken, LC::class, content)

class MyLifecycleComponent/* : LifecycleComponent */
object Stats : NavToken<NavArgs>

fun main() {
    val record = screen(Stats) { component: MyLifecycleComponent ->
        //why is this working ^^
    }
    
    //this is correctly failing because of types
    NavRecord(Stats, MyLifecycleComponent::class, { lc: MyLifecycleComponent -> })
    record.execute(MyLifecycleComponent())
}
but not sure why the
screen(...)
isn't compiler error
l

Landry Norris

07/19/2022, 3:43 PM
The type of Stats is NavToken<NavArgs>. Screen wants a NavToken<T>, where T is a subclass of NavArgs. This is valid.
j

Jiri Bruchanov

07/19/2022, 3:44 PM
That's imo unrelated
Copy code
class MyLifecycleComponent : LifecycleComponent
having ^ type as expected just compiles fine
but for some reason, using
Copy code
val record = screen(Stats) { component: MyLifecycleComponent ->
        //why is this working ^^
}
just doesn't care if
MyLifecycleComponent
is NOT
LifecycleComponent
l

Landry Norris

07/19/2022, 3:46 PM
Same thing with the function taking in a subclass of LifecycleComponent. It says it needs LC where LC is a subclass of LifecycleCompenent. MyLifecycleComponent is a valid subclass of LifecycleComponent.
I see that it’s commented out now.
j

Jiri Bruchanov

07/19/2022, 3:48 PM
I'd like to see also
Copy code
val record = screen(Stats) { component: MyLifecycleComponent -> }
^ to be a compiler issue as
MyLifecycleComponent
is NOT
LifecycleComponent
image.png