Search⌘ K
AI Features

Extension Functions and Properties

Explore how Kotlin extension functions and properties enable you to add functionality to existing classes without modifying their code. Understand the underlying static function mechanism and how extension properties use getters and setters instead of fields. This lesson helps you write cleaner, more modular Kotlin code by leveraging these extensions effectively.

We'll cover the following...

Extension functions

Let’s examine the Java bytecode generated from a Kotlin extension function:

Kotlin 1.5
fun String.remove(value: String) = this.replace(value, "")
fun main() {
println("A B C".remove(" ")) // ABC
}

As a result, we should see the following code:

Java
final class PlaygroundKt {
public static final String remove(
String $this$remove,
String value
) {
// Null-check using a conditional operator
$this$remove = ($this$remove != null) ? $this$remove : "";
value = (value != null) ? value : "";
// Use standard Java replace method
return $this$remove.replace(value, "");
}
public static void main(String[] args) {
// parameter not-null check
String var1 = remove("A B C", " ");
System.out.println(var1);
}
}
...