[2023] Kotlin Tutorial Part 2 Object-Oriented and Functional Programming Chapter 14 Generics 14.1 Generic Functions 14.1.4 Nullable Parameter Types

[2023] Kotlin Tutorial

insert image description here

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)
}

insert image description here

In this way, if a null value is passed, a compilation error will occur

Guess you like

Origin blog.csdn.net/weixin_44226181/article/details/130038064