[2023] Kotlin Tutorial
Article directory
Part II Object Oriented and Functional Programming
Chapter 14 Generics
Use generics to maximize code reuse, protect type safety, and improve performance. The biggest impact of the generic feature on Kotlin is the use of generics in collections.
14.1 Generic functions
Generics can be applied to function declarations, property declarations, generic classes, and generic interfaces.
14.1.4 Nullable parameter types
In a generic function declaration, there is no generic constraint on the type parameters, and the function can receive parameters of any type, including nullable and non-nullable data. For example, fun <T> isEquals(a:T,b:T): Boolean function can pass nullable or non-nullable data when calling, the code is as follows:
println(isEquals(null , 5)) // false
All type parameters without generic constraints are actually limited types, but Any?, Any? can be the root class of any nullable type, and is also compatible with non-nullable types.
If you don't want to receive any nullable data, you can use Any as the constraint type. Any is the parent class of any non-nullable type. The code is as follows:
private fun <T : Any> isEquals(a: T, b: T): Boolean {
return (a == b)
}
In this way, if a null value is passed, a compilation error will occur