https://kotlinlang.org logo
a

andylamax

07/03/2020, 10:32 AM
While we are at generics, What is the difference between
fun <T> Foo()
and
fun <T:Any> Foo()
? So far I have just been using IntelliSense suggestions. I wan't to understand more. Any deep explanation?
d

diesieben07

07/03/2020, 10:33 AM
First one allows nullable types (e.g.
String?
) for
T
, the 2nd one does not.
a

araqnid

07/03/2020, 10:33 AM
T: Any
specifies that T is a non-null type (
Any?
is the ultimate supertype)
a

andylamax

07/03/2020, 10:34 AM
so, there is no difference between
fun <T:Any?> Foo()
and
fun <T> Foo()
?
a

araqnid

07/03/2020, 10:35 AM
right,
<T>
is effectively
<T:Any?>
a

andylamax

07/03/2020, 10:36 AM
Then, I am glad. My thirst is quenched. Thank you
👍🏻 5
m

Md Sajid Shahriar

07/03/2020, 10:45 AM
If we see the decompiled byte code to java(wanted to post the byte code but this is much more readable) for
fun <T:Any> foo(t:T)
Copy code
public final void foo(@NotNull Object t) {
   Intrinsics.checkParameterIsNotNull(t, "t");
}
fun <T:Any?> foo(t:T)
Copy code
public final void foo(Object t) {
}
fun <T> foo(t:T)
Copy code
public final void foo(Object t) {
}
fun <T> foo(t:T?)
Copy code
public final void foo(@Nullable Object t) {
}
So yeah to the compiler is basically the same for
<T:Any?>
and
<T>
👍 5
2 Views