Kotlin Generics
Generics mean "parameterized types", using types as parameters as well.
With generics, the same class or function can safely handle data of many types while leaving type checking to the compiler.
Kotlin's generics are similar to Java's, but use declaration-site variance instead of wildcards, making the syntax more uniform and safer to use.
Generic class
Declare a type parameter by adding a pair of angle brackets after the class name; this parameter can then be used as a type in the class's properties and methods.
Example
// T is a type parameter; its concrete type is determined when an instance is created
class
Box
<
T
(
t:
T
)
{
var value
=
t
}
fun main
(
)
{
val boxInt
=
Box
<
Int
(
10
)// Explicitly specify T as Int
val boxString
=
Box
(
"RUNOOB"
)
// Omit the type parameter and the compiler infers Box
println
(
boxInt.
value
)
println
(
boxString.
value
)
}
The output is:
10
RUNOOB
You can declare multiple type parameters or add constraints to them; these topics are covered in later sections.
Generic functions
A generic function's type parameter is written between the fun keyword and the function name.
Example
class
Box
<
T
(
t:
T
)
{
var value
=
t
}
// The type parameter T goes between fun and the function name
fun
<
T
boxIn
(
value:
T
)
=
Box
(
value
)
fun main
(
)
{
val box1
=
boxIn
<
Int
(
1
)// Explicitly specify the type parameter
val box2
=
boxIn
(
"runoob"
)
// Let the compiler infer the type parameter
println
(
box1.
value
)
println
(
box2.
value
)
}
The output is:
1
runoob
Inside a generic function, you can use is to check a parameter's type and take different branches for different types.
Example
fun main
(
)
{
val age
=
23
val name
=
"runoob"
val bool
=
true
doPrintln
(
age
)
Inferred as doPrintln
doPrintln
(
name
)
Inferred as doPrintln
doPrintln
(
bool
)
Inferred as doPrintln
}
fun
<
T
doPrintln
(
content:
T
)
{
when
(
content
)
{
is Int
->
println
(
"The integer is $content"
)
// uppercase() replaced the deprecated toUpperCase() starting in Kotlin 1.5
is
String
->
println
(
"String converted to uppercase: ${content.uppercase()}"
)
else
->
println
(
"T is neither an integer nor a string"
)
}
}
The output is:
整型数字为 23
字符串转换为大写:RUNOOB
T 不是整型,也不是字符串
Type Inference
The Kotlin compiler tries to infer type parameters from parameters and return values; when it can, you can omit the contents of the angle brackets.
You only need to write them explicitly when inference is impossible, such as when the parameter position provides no type information or you want a broader type.
Example
// No parameter can be used to infer T; it must be determined by the assignment target or explicit specification
fun
<
T
nothing
(
):
T
?
=
null
fun main
(
)
{
val inferred
=
listOf
(
"runoob"
,
"kotlin"
)
// Inferred as List
val explicit
:
List
<
Any
=
listOf
(
"runoob"
,
42
)// Inferred as List from the declared type
val empty
:
String
?
=
nothing
(
)
// T inferred as String from the assignment target
println
(
inferred
)
println
(
explicit
)
println
(
empty
)
}
The output is:
[runoob, kotlin]
[runoob, 42]
null
Note:Type parameters exist only at compile time; type erasure is performed at runtime.List
and List They are the same class at runtime, so you cannot write value is T; you need to combine it with reified to make it work, which will be explained in the last section of this chapter.
Generic constraints
Constraints limit the range of values allowed for a type parameter, written by adding a colon and an upper bound after the type parameter.
Upper bound constraints
The most common constraint is the upper bound, meaning T must be a subtype of a certain type.
Example
// T must be a subtype of Comparable
fun
<
T
:
Comparable
<
T
sort
(
list:
List
<
T
):
List
<
T
=list.
sorted
(
)
fun main
(
)
{
println
(
sort
(
listOf
(
3
,
1
,
2
)
)
)
println
(
sort
(
listOf
(
"runoob"
,
"kotlin"
,
"www.runoob.com"
)
)
)
}
The output is:
[1, 2, 3]
[kotlin, runoob, www.runoob.com]
If you pass in a type that does not satisfy the constraint, the compiler will report an error immediately.
For example, HashMap
Default upper bound Any?
When no constraint is written, the default upper bound of a type parameter is Any?, meaning T is allowed to be a nullable type.
Example
// No constraint is written, so the upper bound defaults to Any?, and T can be nullable
fun
<
T
echo
(
value:
T
)
:
String
=
"Received: $value"
fun main
(
)
{
println
(
echo
(
"runoob"
)
)
println
(
echo
(
42
)
)
println
(
echo
<
String
?>
(
null
)
)// Explicitly specify T as String?
}
The output is:
收到:runoob
收到:42
收到:null
If you want the type parameter to be non-null, just write the upper bound as Any; in that case echo
Multiple constraints with where
When multiple upper bounds must be satisfied at once, list them together using a where clause.
Example
// T satisfies two constraints at once: a subtype of CharSequence and comparable
fun
<
T
copyWhenGreater
(
list:
List
<
T
, threshold
:
T
)
:
List
<
String
where T
:
CharSequence,
T
:
Comparable
<
T
{
returnlist.
filter
{
it
threshold
}
.
map
{
it.
toString
(
)
}
}
fun main
(
)
{
val list
=
listOf
(
"runoob"
,
"kotlin"
,
"www.runoob.com"
)
println
(
copyWhenGreater
(
list,
"kotlin"
)
)
}
The output is:
[runoob, www.runoob.com]
Variance
Variance addresses the question of whether "Box
Kotlin does not have wildcard types like Java; it offers two mechanisms: declaration-site variance and use-site variance.
Declaration-site variance: out and in
Adding out to a type parameter means covariance; it may appear only in output positions, that is, as a return value.
Example
// out A: A appears only as a return value, so Producer
class
Producer
<
out A
(
private
val value
:
A
)
{
fun get
(
)
:
A
=
value
}
fun main
(
)
{
val strProducer
:
Producer
<
String
=
Producer
(
"RUNOOB"
)val anyProducer
:
Producer
<
Any
=
strProducer// Covariance: a subtype assigned to a supertype
println
(
anyProducer.
get
(
)
)
}
The output is:
RUNOOB
Adding in to a type parameter means contravariance; it may appear only in input positions, that is, as a parameter.
Example
// in A: A appears only as a parameter, so Consumer
class
Consumer
<
in A
{
fun consume
(
value
:
A
)
{
println
(
"Consume: $value"
)
}
}
fun main
(
)
{
val anyConsumer
:
Consumer
<
Any
=
Consumer
<
Any
(
)val strConsumer
:
Consumer
<
String
=
anyConsumer// Contravariance: a supertype assigned to a subtype
strConsumer.
consume
(
"runoob"
)
}
The output is:
消费:runoob
A handy rule: producers use out, consumers use in.
If a parameter marked out is used as a parameter type, or one marked in is used as a return type, the compiler will report an error.
Use-site variance (type projection)
Some types are not defined by you, so you cannot add modifiers at the declaration site; in that case you can apply a type projection at the use site.
Example
// Array is invariant, so Array
// Write the parameter as Array
fun copy
(
from
:
Array
<
out Any
, to
:
Array
<
Any
)
{
for
(i in from.
indices
)
{
to
[
i
]
=
from
[
i
]
}
}
fun main
(
)
{
val src
=
arrayOf
(
"runoob"
,
"kotlin"
)
// Array
val dst
=
Array
<
Any
(
2
)
{
""
}// Array
copy
(
src, dst
)
println
(
dst.
joinToString
(
)
)
}
The output is:
runoob, kotlin
Conversely, if a parameter is only written to, you can project it as in, meaning it can accept a broader type.
Star projections
When you do not care at all what the type argument is and just want to use the generic type safely, you can use a star projection *.
A star projection can be understood as a "read-only or write-only safe projection"; its exact meaning depends on the variance of the type parameter.
| Type declaration | Foo<*> is equivalent to | Safe to read | Safe to write |
|---|---|---|---|
| class Foo |
Foo |
Can read values of type TUpper | Cannot write |
| class Foo |
Foo |
No value can be safely read | Cannot write any value |
| class Foo |
Read: Foo
|
Can read values of type TUpper | Cannot write |
The most common use case is List<*>, which represents a read-only list with an unknown element type; iterating and reading is safe.
Example
// Accept a read-only list of any element type
fun printAll
(
list
:
List
<*>
)
{
for
(
item in list
)
{
println
(
item
)
}
}
fun main
(
)
{
printAll
(
listOf
(
1
,
2
,
3
)
)
printAll
(
listOf
(
"runoob"
,
"kotlin"
)
)
}
The output is:
1
2
3
runoob
kotlin
If a generic type has multiple type parameters, each one can be projected individually.
Take the standard library's Function1
Note:Star projections look similar to Java's raw types, but star projections are safe: the compiler prevents you from writing values into them, whereas Java's raw types bypass type checking. Also,MutableList<*> can only be read Any?, calling add will fail to compile, because the compiler cannot determine what type should be written.
Generics and reified
Ordinary generics are erased at runtime, so you cannot directly perform an is T check or call T::class.
Declaring a function as inline and adding reified to its type parameter makes the compiler inline the type argument directly into the code, thereby preserving type information.
Example
// reified can only be used on type parameters of inline functions
inline fun
<
reified T
typeName
(
)
:
String
=
T
::
class
.
simpleName
?:
"File %s type is: %s%n"
inline fun
<
reified T
isType
(
value
:
Any
)
:
Boolean
=
value is T
fun main
(
)
{
println
(
typeName
<
String
(
)
)
println
(
typeName
<
Int
(
)
)
println
(
isType
<
String
(
"RUNOOB"
)
)
println
(
isType
<
Int
(
"RUNOOB"
)
)
}The output is:
String
Int
true
false
The standard library's filterIsInstance
Example
fun main
(
)
{
val mixed
:
List
<
Any
=
listOf
(
"runoob"
,
42
,
"kotlin"
,
3.14
)val strings
=
mixed.
filterIsInstance
<
String
(
)
println
(
strings
)
}The output is:
[runoob, kotlin]
Note:reified The cost is that the function must be inlined, with code copied to every call site and a larger binary. It has been available since Kotlin 1.0, but it is not suitable in every scenario; use it only when runtime type information is truly needed.
Common questions
Below are the most common issues encountered when using generics.
| Problem | Reason | Solution |
|---|---|---|
| Cannot check value is T at runtime | Generics are subject to type erasure | Add reified to the type parameter of an inline function |
| Array
|
Arrays are invariant | Declare the parameter as Array |
| Method parameter error after adding out | A covariant type parameter cannot appear in an input position | Remove out, or switch to a use-site projection |
| Passing null to a generic function reports an error | The upper bound is restricted to a non-null type | Widen the upper bound to Any? or explicitly specify a nullable type argument |
| MutableList |
The compiler does not know what type should be written | Use a concrete type instead, or switch to a read-only List<*> |