+ 1

What does <T> mean in Kotlin?

kotlinlang.org uses <T> on many pages but doesn't explain it. Can you actually use it in your code, or is it just a way that people who write compilers (such as Andrey Breslav) like to say "put a real type in here when you actually code something"?

29th Jul 2023, 2:24 AM
Rain
Rain - avatar
8 odpowiedzi
+ 5
yes, T a shorthand for some real type. learn generics in Kotlin: https://kotlinlang.org/docs/generics.html#variance
29th Jul 2023, 4:26 AM
Bob_Li
Bob_Li - avatar
+ 4
Runtime Terror , Followup: I happened to see this on Baeldung. "the diamond operator <>" https://www.baeldung.com/java-generics So I searched for "Java diamond operator" and found a ton of sites that call it that. However, it's not actually an operator according to Oracle. "This pair of angle brackets is informally called the diamond." https://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html So there's something we can call it, even if it's not official.
1st Aug 2023, 10:10 AM
Rain
Rain - avatar
+ 3
<T> is a naming convention, try <Rain> or <Bob_Li> It works too
29th Jul 2023, 6:07 PM
RuntimeTerror
RuntimeTerror - avatar
+ 2
I don't think there's a name for <> maybe there is tho, I'm not sure... I always see it as part of the syntax in generic programming
29th Jul 2023, 10:28 PM
RuntimeTerror
RuntimeTerror - avatar
+ 1
Bob_Li , Ah. So I *can* use <T> in my code. Thanks. class Box<T>(t: T) { var value = t } fun main() { val box: Box<Int> = Box<Int>(1) println(box.value) val boxx: Box<Long> = Box<Long>(1_000_000_000) println(boxx.value) } // Output: // 1 // 1000000000
29th Jul 2023, 6:13 AM
Rain
Rain - avatar
+ 1
Runtime Terror , Interesting. So is there a name for these angle brackets in that context? < > There's nothing about them under "Operators and Special Symbols" ( https://kotlinlang.org/docs/keyword-reference.html#operators-and-special-symbols ), which only contains, < > <= >= ..< // new range operator like until -> // separator has three uses
29th Jul 2023, 9:14 PM
Rain
Rain - avatar
+ 1
Good to know that, I've never met myself in a situation where I'm asked to say the name lol 😀
1st Aug 2023, 10:45 AM
RuntimeTerror
RuntimeTerror - avatar
0
Runtime Terror , Maybe over the phone. Heh.
1st Aug 2023, 8:43 PM
Rain
Rain - avatar