当我们可以使用它时,我需要一个现实生活中的例子。我已经浏览了这个链接(https://kotlinlang.org/docs/reference/inline-functions.html),但找不到一个很好的例子。
所以假设我们有一个高阶函数,它接受另一个函数作为参数
fun doSomething(block: () -> Unit){
}
Run Code Online (Sandbox Code Playgroud)
Kotlin 编译器会将其转换为等效的 Java 代码,即,
void doSomething( new Function(){
void invoke(){
// the code which you passed in the functional parameter
}
})
Run Code Online (Sandbox Code Playgroud)
Kotlin 编译器为您传递的功能参数创建一个匿名内部类,当您调用此传递的功能参数时,编译器会在内部调用此invoke()方法。
因此,所有功能参数都会导致额外的对象创建和函数调用,这是性能和内存开销。
我们可以通过引入inline修饰符来避免这种开销。当添加到函数时,函数调用被跳过,函数代码被添加到调用站点。
假设我们有一个简单的测试功能,
inline fun testing(block : () -> Unit){
println("Inside the testing block")
block()
someOtherRandomFunction()
}
Run Code Online (Sandbox Code Playgroud)
我们从主函数调用这个测试函数,就像这样
fun main(){
testing{
println("Passed from the main function")
}
}
Run Code Online (Sandbox Code Playgroud)
当上面的主函数被编译时,它看起来像
fun main(){
println("Inside the testing block")
println("Passed from the main function")
someOtherRandomFunction()
}
Run Code Online (Sandbox Code Playgroud)
就好像没有测试函数存在过一样,来自测试函数的所有代码体都被简单地复制粘贴到主函数体中。
| 归档时间: |
|
| 查看次数: |
1384 次 |
| 最近记录: |