Why can’t the compiler infer the type of T for `fo...
# language-evolution
s
Why can’t the compiler infer the type of T for
foo
without me specifying? (I need to include
<Int>
in
val foo: Sealed1.Sub1<Int>
even though they all have the same type) I think it should be able to, so it is in #language-evolution (not in #language-proposals because there may be a good reason why it can’t).
Copy code
val foo: Sealed1.Sub1
    get() = Sealed1.Sub1(
        Sealed2.Sub2(123)
    )
sealed class Sealed1<T>(
    open val value: Sealed2<T>
) {
    data class Sub1<T>(
        override val value: Sealed2<T>,
    ) : Sealed1<T>(value)
}

sealed class Sealed2<T>(value: T) {
    data class Sub2(val myValue: Int): Sealed2<Int>(myValue)
}
y
I believe
val foo: Sealed1.Sub1<_>
should do the trick. The reason is that unqualified (a.k.a raw) generics are not allowed in Kotlin because they are a bit ambiguous. The _ tells the compiler to infer the type param for Sub1. Btw, I believe you can remove the type specification altogether and just do
val foo get() =
s
What version of Kotlin does that syntax (
<_>
) require? I don’t recognize it.
Do you mean
*
?
If so, the issue with that is that I lose type-hinting when I use the properties (
foo.value.myValue + 1
is an error).
e
no,
<_>
is not an error, and means something different than
<*>
y
It's a 1.7.0 addition. It tells the compiler to infer the type as best as it can