Alexander Suraphel
11/07/2021, 2:46 PM*fun* <T : Comparable<T>>
and *fun* <Comparable<T>>
?Rob Elliot
11/07/2021, 2:58 PMfun <Comparable<T>> foo(a: T) {}
won't compile. The bit inside the <...>
has to be a valid type variable name, and Comparable<T>
isn't a valid name because it contains <
and >
.
In fun <T : Comparable<T>> foo(a: T) {}
you are declaring a type variable T
, and then saying that whatever T
actually ends up being at runtime, it must be a subtype of Comparable<T>
. So you will be able to call a.compareTo(TODO())
inside that method.
Where as in fun <T> foo(a: T) {}
, T
could be any type at runtimefun <Comparable> foo(a: Comparable) {}
will compile, but is a really bad idea - because you are declaring a type variable Comparable
that could be anything at runtime (like T
or E
or whatever other type variable name you typically use) but which shadows and so replaces the concrete type Comparable
, so misleadingly suggests a
is actually a subtype of the Comparable
concrete type, when it isn't at all.Alexander Suraphel
11/07/2021, 3:07 PMfun <T: String> foo(a: T) {}
vs fun foo(a: String) {}
? Is there any advantage to the genericRob Elliot
11/07/2021, 3:11 PMString
is final, so you cannot have a subtype of it, so I can't see when a generic type T : String
would ever be useful - if you can call the function and it compiles, T
will always actually be String
. I think.
A good rule of thumb is never make a function generic unless you have a real use case for it.