gpt4 book ai didi

android - kotlin 中内联函数的正确用法是什么?

转载 作者:行者123 更新时间:2023-12-02 12:19:31 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





when to use an inline function in Kotlin?

(7 个回答)


2年前关闭。




当我们可以使用它时,我需要一个真实的例子。我已经浏览了这个链接(https://kotlinlang.org/docs/reference/inline-functions.html)但找不到一个很好的例子。

最佳答案

所以假设我们有一个高阶函数,它接受另一个函数作为参数

fun doSomething(block: () -> Unit){

}

Kotlin 编译器会将其转换为等效的 Java 代码,即
void doSomething( new Function(){

void invoke(){
// the code which you passed in the functional parameter
}

})

Kotlin 编译器为您传递的功能参数创建一个匿名内部类,当您调用此传递的功能参数时,编译器在内部调用此 invoke()方法。

结果,所有功能参数都会导致额外的对象创建和函数调用,这是性能和内存开销。

我们可以通过引入 inline 来避免这种开销。修饰符。添加到函数时,会跳过函数调用,而是在调用站点添加函数代码。

假设我们有一个简单的测试功能,
inline fun testing(block : () -> Unit){ 

println("Inside the testing block")
block()
someOtherRandomFunction()

}

我们从主函数中调用这个测试函数,像这样
fun main(){

testing{
println("Passed from the main function")
}

}

当上面的 main 函数被编译时,它看起来像
fun main(){

println("Inside the testing block")
println("Passed from the main function")
someOtherRandomFunction()

}

好像从来没有测试函数一样,测试函数的所有代码体都只是简单地复制粘贴到主函数体中。

关于android - kotlin 中内联函数的正确用法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59543501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com