+ 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"?
8 Réponses
+ 5
yes, T a shorthand for some real type.
learn generics in Kotlin:
https://kotlinlang.org/docs/generics.html#variance
+ 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.
+ 3
<T> is a naming convention, try <Rain> or <Bob_Li>
It works too
+ 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
+ 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
+ 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
+ 1
Good to know that, I've never met myself in a situation where I'm asked to say the name lol 😀
0
Runtime Terror ,
Maybe over the phone. Heh.