In this episode of learning kotlin, we look at 3 important keywords – inline, noinline and crossinline. The inline keyword is super common and you’ve probably run across this one at some point. What does it mean and when is it useful? We also look at the related but seldom used variants noinline and crossinline.
Show Notes
Code Snippets:
Simple inlined function:
// Kotlin
fun main(args: Array<String>) {
functionA()
}
inline fun functionA() {
println("awesomeness !")
}
Warning: Expected performance impact of inlining ‘public inline fun functionA() can be insignificant. Inlining works best for functions with lambda parameters
What the code looks like in Java:
public static final void main(String[] args) {
String var1 = "awesomeness !";
System.out.println(var1);
}
Function with lambda parameter:
fun main(args: Array<String>) {
functionA({
println("double awesomeness")
})
}
inline fun functionA(lambda: () -> Unit) {
println("awesomeness !")
lambda.invoke()
}
What the code looks like in Java (without inline):
public static final void main(String[] args) {
functionA(new Function() {
println("double awesomeness")
});
}
public static final void functionA(Function0 lambda) {
String var1 = "awesomeness !";
System.out.println(var1);
lambda.invoke();
}
What the code looks like in Java (with inline):
public static final void main(String[] args) {
String var1 = "awesomeness !";
System.out.println(var1);
String var2 = "double awesomeness";
System.out.println(var2);
}
Function0:
public interface Function0<out R> : Function<R> {
/** Invokes the function. */
public operator fun invoke(): R
}
Misc:
- PublishedApi annotation
- Matt Logan’s post on inline keyword
- Ben Daniel Medium post – inline, noinline, crossinline — What do they mean?
Sponsors
- Microsoft AppCenter – Sign up now on appcenter.ms and spend less time managing your app lifecycle and more time coding.
Contact
- @fragmentedcast [twitter.com]
- @donnfelker and 📷 donnfelker
- @kaushikgopal and 📷 kaushikgopal