kotlin内联函数
In this tutorial, we’ll be looking into Kotlin inline function. We’ll follow that with Reified Type Parameters.
在本教程中,我们将研究Kotlin内联函数。 我们将在后面加上Reified Type Parameters。
Kotlin内联函数 (Kotlin inline functions)
We’ve discussed Kotlin Higher Order Functions and Lambda Expressions before.
They’re super useful in passing functions as parameters. But these functions are objects which have there own callbacks and subsequently memory allocations. Let’s understand how these functions passed as parameters internally work through an example.
我们之前已经讨论过Kotlin高阶函数和Lambda表达式 。
在将函数作为参数传递时,它们非常有用。 但是这些函数是具有自己的回调以及随后的内存分配的对象。 让我们通过示例了解如何将这些函数作为参数传递给内部。
fun main(args: Array<String>) {
println("Hey how are you doing")
sampleFunction("JournalDev.com", ::println)
}
fun sampleFunction(str: String, expression: (String) -> Unit) {
println("This is Kotlin Inline Functions Tutorial")
expression(str)
}
sampleFunction
when run passes println
as the parameter. Now Kotlin is a JVM based language so everything is converted into bytecode. Let’s look at the bytecode of the above code by going to Tools | Kotlin | Show Bytecode.
运行时的sampleFunction
将println
作为参数传递。 现在Kotlin是一种基于JVM的语言,因此所有内容都将转换为字节码。 让我们通过转到“ 工具” |“工具栏” |查看上面代码的字节码。 Kotlin| 显示字节码 。
The main part expression.invoke()
. Invoking the lambda expression (println) would create an additional call and hence memory. The invoke method looks like this in Java:
主要部分是expression.invoke()