When creating generic function what is the differe...
# getting-started
a
When creating generic function what is the difference between
*fun* <T : Comparable<T>>
and
*fun* <Comparable<T>>
?
r
fun <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 runtime
👍 1
fun <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.
a
What about
fun <T: String> foo(a: T) {}
vs fun
foo(a: String) {}
? Is there any advantage to the generic
r
String
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.
🙏 1
👍 3