Hi, in the section on Declaration-site variance he...
# getting-started
m
Hi, in the section on Declaration-site variance here https://kotlinlang.org/docs/reference/generics.html#declaration-site-variance there is an example
Copy code
interface Source<out T> {
    fun nextT(): T
}

fun demo(strs: Source<String>) {
    val objects: Source<Any> = strs // This is OK, since T is an out-parameter
    // ...
}
If I replace String by a type argument T, it no longer compiles and says "Type mismatch: inferred type is Source<T> but Source<Any> was expected". Why is that? I had expected it work just like in the example.
n
guessing, but it's probably not guaranteed to be the same
T
m
For reference, this is the code I'm trying to compile.
Copy code
interface Source<out T> {
    fun nextT(): T
}

fun <T> demo(strs: Source<T>) {
    val objects: Source<Any> = strs // Type mismatch: inferred type is Source<T> but Source<Any> was expected
}
As far as I can see there is only one T in demo(), and so it doesn't need to be "the same" as anything else?
regardless of what T is, it should be possible to upcast Source<T> to Source<Any>.
a
Any
isn’t the ultimate supertype,
Any?
is
If
T
is non-nullable, you should specify
<out T : Any>
by contrast,
String
is a subtype of
Any
, so it’s consistent that that would work
or you can write
Source<Any?>
if that’s what you meant
m
Oh alright, that makes a lot of sense. Thanks.
t
this is my favourite source of generics compile errors, I am basically ignoring
Any?
at least once a week and still think
Any
is the ultimate supertype when writing, just to have the compiler reminding me I once again forgot about nulls
😀 1
m
If the compiler was slightly better at reading my mind it could probably have produced an error message that made my error obvious to me. E.g. "Type mismatch: inferred type is Source<T: Any?> but Source<Any> was expected"
t
I heard Rust has a pretty good compiler when it comes to error notification. maybe the next area of improvement for kotlin could be to look at the Rust compiler and take some inspiration