Hey, I'm having some issues with a generic type co...
# getting-started
l
Hey, I'm having some issues with a generic type constraint with a star projection, I'm not sure if I'm missing something.
Copy code
interface First {
    fun foo()
}

interface Second {
    fun bar()
}

data class FirstAndSecond<T>(val value: T) where T : First, T : Second

fun main() {
    val thing: FirstAndSecond<*> = null!! // pretend there's a real instance here
    thing.value.foo()
    thing.value.bar() // Unresolved reference: bar
}
I would expect
thing.value
here to implement both First and Second as per the type constraint, but it's only ever using the first type constraint (interestingly the first defined one takes priority, if I swap them around I can access bar() but not foo()). Am I misunderstanding how this works, or have I run into a Kotlin limitation?
s
I think this is https://youtrack.jetbrains.com/issue/KT-7389 and is fixed in Kotlin 2.0
1
In the meantime you can work around it with a generic function:
Copy code
fun <T> fooBar(thing: T)  where T : First, T : Second {
  thing.foo()
  thing.bar()
}
l
Funny you should mention, I literally just tested with K2 and it seemed to work. Thanks for your help 😄
k
There's also this workaround:
Copy code
(thing.value as First).foo()
    (thing.value as Second).bar()