'Interfering type parameter based on another type parameter
Is it possible to Kotlin Compiler to infer type parameter based on another type parameter?
That is: infere type A based on type B in IntExample class definition.
interface Something<A>
interface Example<A, B: Something<A>>
class IntSomething: Something<Int>
// Can Int type parameter be infered by the fact that IntSomething is Something<Int>?
// If yes, how could I specify B type parameter without specifing the infered A (Int) parameter?
class IntExample: Example<Int, IntSomething> // specifing Int here is painful!!!
Imagine that we have more type parameters like that - it will be a lot of boilerplate to specify each of them if some might (theoretically) be infered.
EDIT
After an exhausive respose from @KarstenGabriel I will extend the previous example, to make it clear what for are the type parameters used here:
interface Something<A> {
val sth: A
}
interface Example<A, B: Something<A>> {
val eg: A
val something: B
}
data class IntSomething(override val sth: Int): Something<Int>
data class DescribedIntSomething(
override val sth: Int,
val description: String
): Something<Int>
data class DescribedIntExample(
override val eg: Int,
override val something: DescribedIntSomething,
): Example<Int, DescribedIntSomething> // specifing Int here is painful
fun main() {
val describedIntExample = DescribedIntExample(
eg = 1,
something = DescribedIntSomething(1, "Just one")
)
// We have to know that something is DescribedIntSomething to read description.
// Neither `*` nor `Something<Int>` is sufficient, we need `B: Something<Int>` to keep B
val description = describedIntExample.something.description
println(description)
}
So we use the type parameters - A and B as return values from eg and something
- Wildcard
*cannot be used as it is just meansAny?. We need to keep concrete typeB. (eg. to enable reading descrption in the example) - Wildcard
Something<Int>cannot be used instead ofB: Something<Int>for thesame reason as in the point 1
Maybe it's just an language design level. The type parameters do exists in compile time (they are ereased later), so theoretically Example<DescribedIntSomething> might be sufficient instead of Example<Int, DescribedIntSomething> as DescribedIntSomething is Something<Int>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
