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

Lucy Poulton

11/13/2023, 3:41 PM
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

Sam

11/13/2023, 3:58 PM
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

Lucy Poulton

11/13/2023, 3:59 PM
Funny you should mention, I literally just tested with K2 and it seemed to work. Thanks for your help 😄
k

Klitos Kyriacou

11/13/2023, 4:08 PM
There's also this workaround:
Copy code
(thing.value as First).foo()
    (thing.value as Second).bar()