[2023] Kotlin Tutorial Part 2 Object-Oriented and Functional Programming Chapter 13 Functional Programming Cornerstone - Higher-order Functions and Lambda Expressions 13.5 Inline Functions 13.5.1 Custom Inline Functions

[2023] Kotlin Tutorial

insert image description here

Part II Object Oriented and Functional Programming

Chapter 13 The Cornerstone of Functional Programming—Higher-order Functions and Lambda Expressions

Although the idea of ​​functional programming is as old as object-oriented, the computer language that supports functional programming is only a matter of recent years. These languages ​​include Swift, Python, Java 8, and C++ 11. As a new language, Kotlin also supports functional programming.

13.5 Inline functions

In a high-order function, if the parameter is a function type, it can receive a Lambda expression, and the Lambda expression is compiled into an anonymous class at compile time, and an object will be created every time the function is called. If this is called repeatedly by the function, then Creating many objects will incur runtime overhead.

To solve this problem, such functions can be declared as inline functions in Kotlin.

[Tips] The inline function will not generate function call code when compiling, but replace each function call with the actual code in the function body.

13.5.1 Custom Inline Functions

The Kotlin standard library provides many commonly used inline functions. Developers can customize inline functions. However, if the function parameter is not a function type and cannot receive Lambda expressions, then such functions are generally not declared as inline functions. Declaring an inline function needs to be modified with the keyword inline .

Take a chestnut:

// 内联函数
inline fun calculatePrint(funN: (Int, Int) -> Int) {
    
    
    println("${
      
      funN(10, 5)}")
}

fun main() {
    
    

    calculatePrint {
    
     a, b -> a + b }
    calculatePrint {
    
     a, b -> a - b }
}

The above code declares an inline function calculatePrint whose parameter is (Int,Int)->Inta function type that can receive Lambda expressions.

insert image description here

おすすめ

転載: blog.csdn.net/weixin_44226181/article/details/130024499