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

Mattias Flodin

08/06/2020, 5:37 PM
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

nanodeath

08/06/2020, 5:40 PM
guessing, but it's probably not guaranteed to be the same
T
m

Mattias Flodin

08/06/2020, 5:42 PM
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

araqnid

08/06/2020, 6:16 PM
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

Mattias Flodin

08/06/2020, 6:31 PM
Oh alright, that makes a lot of sense. Thanks.
t

thanksforallthefish

08/07/2020, 6:36 AM
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

Mattias Flodin

08/07/2020, 6:56 AM
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

thanksforallthefish

08/07/2020, 9:00 AM
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