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

James Whitehead

01/01/2022, 7:36 PM
Hi 👋 • What is the correct way to write a function signature using generics, whereby the first parameter is something like 
<T>
 and the second parameter is "an instance or implementation of T"? • Also kind of related question: When should one use
<T>
vs
<T : Any>
, I'm not really sure what the difference is? Thanks in advance 🙂
j

Joffrey

01/01/2022, 8:08 PM
For your first question, do you mean "T or a subtype of T"? I guess this should work:
Copy code
fun <T, U : T> someFunction() {

}
👍 1
🙏 1
For the second question,
<T>
denotes any type including nullable types, while
<T : Any>
forbids nullable types for T, because nullable types are not subtypes of
Any
🙏 1
1
👍 1
j

James Whitehead

01/01/2022, 9:33 PM
Yes that's right, "T or a subtype of T" is what I was going for 🙂 Is there a convention for knowing which letter to use for a generic type? I.e. In your example you have used
U
, how did you know to use that particular letter?
Thank you, second answer makes perfect sense to me now!
j

Joffrey

01/01/2022, 10:32 PM
The letters are arbitrary, it's like variable names. The usual convention is to use single letters, but sometimes even whole words are used.
T
is a very classic example, because it's T as in "Type".
U
is simply the next letter in the alphabet. Sometimes other letters make sense. For instance
K
and
V
for the types of the keys and values in a map, or
E
for the element type in a collection.
🙏 1
👍 1
j

Jacob

01/02/2022, 12:40 AM
Letters are arbitrary but only under VERY special circumstances should you EVER use a more than one char name for a type parameter. Breaking the one char convention can make things get really confusing
👍 1
🙏 1
j

James Whitehead

01/02/2022, 6:09 AM
Thank you very much @Joffrey and @Jacob makes much more sense to me now 🙂 I used to be PHP dev so generics are something I'm still getting my head around after transitioning to Java/Kotlin
j

Joffrey

01/02/2022, 7:30 AM
@Jacob yes, single letters are a very common convention indeed, but I've seen 2-letter names used quite regularly too. That said I would also strongly suggest to stick to single letters, unless you have a good reason to do differently. Sometimes it may be interesting to use a different convention if you're trying to match a scientific paper's names for an algorithm you're implementing, or if your types represent things with the same initial and you need a second letter
👍 1
m

Matteo Mirk

01/04/2022, 11:49 AM
I’ve seen some codebases using a whole WORD as a type identifier, such as Assertj
2 Views