Definition: An inline function is a normal function preceded by an inline keyword modifier.
Features of inline functions: Inline functions are copied to the place of call at compile time.
Inline functions are usually used in higher-order functions to improve the performance of higher-order functions. During a higher-order function call, a closure (function object) is generated for the internal function, and the virtual machine allocates memory for the closure object (class and function object). The virtual machine also introduces some extra overhead during the call. With inline functions, there is no overhead of creating objects and managing object references.
fun main(a) {
hello {
println("write kotlin...")}}inline fun hello(block: () -> Unit) {
println("before block")
block()
}
Copy the code
Limitations of inline functions:
Inline increases the amount of code, so avoid large inline functions.
An inline function cannot hold a reference to an passed function argument, nor can it pass an passed function argument to a function outside the forest.
The noinline keyword disables inlining
If you want to save function type parameters, use the noinline keyword before the function parameters to disable inline.
If you need to pass function arguments to another function, using noinline will not improve performance, so inline functions are not recommended.
Lambda expressions cannot contain their own returns and cannot use return directly. Lambda is allowed if it is inline, which is called a nonlocal return.
Specify type parameters
Normally we use parameter types. In this way we need to specify the class and the specific instance parameter T
fun <T> TreeNode.findParentOfType(clazz: Class<T>): T? {
var p = parent
while (p ! =null && !clazz.isInstance(p)) {
p = p.parent
}
@Suppress("UNCHECKED_CAST")
return p as T?
}
/ / call
treeNode.findParentOfType(MyTreeNode::class.java)
Copy the code
Inline functions that support externalized types need only specify the reified type
inline fun <reified T> TreeNode.findParentOfType(): T? {
var p = parent
while (p ! =null&& p ! is T) {
p = p.parent
}
return p as T?
}
/ / callMyTree. FindParentOfType < MyTreeNodeType > ().Copy the code
Using reified in inline function specifies types, inline function can copy a function to call, at compile time, knew the type information, at the time of newly generated bytecode can specify type information, and use the type information, not used in Java types to clear, so the whole process does not need to specify the class object.
One example used in the previous article is when you start an activity
inline fun <reified T : Activity> Activity.startActivity(context: StartActivity (Intent(Context, T::class.java))} // Use startActivity<NewActivity>(Context)Copy the code
Reified simplifies the argument by passing the object type directly and fetching the class object at runtime.