Kotlin Extension Function with Best Practice

Kotlin Extension Function

What are Kotlin extension functions?

Extension functions in Kotlin are like adding superpowers to objects without changing the original object. Let me explain it in a simple way:

Imagine you have a toy car, and it can do some cool things like moving forward and backward. But one day, you wish it could also make cool sounds like a real car.

Extension functions are like adding a special button to your toy car that makes it play car sounds. But here’s the cool part: you don’t have to change the car itself. You just add this magical button, and suddenly your toy car can do more things!

In Kotlin, extension functions work similarly. They let you add new functions to existing classes (objects) without changing the original class’s code. So, if you have a regular object, you can make it do extra tricks using extension functions.

Here are some key points to understand about extension functions:

  1. No Need to Modify Existing Code: You can create extension functions without changing the code of the original class. This is particularly useful when dealing with classes from libraries or third-party code.
  2. Usage Like Regular Methods: Once you define an extension function, you can use it just like any other method of the class. It looks and feels as if it’s part of the class, even though it’s added externally.
  3. Syntax: An extension function is defined outside the class it extends. To declare one, you specify the type you’re extending, followed by a dot (.), the name of your function, and the function body.

1. Declaring an Kotlin Extension Function:

fun ClassName.extensionFunctionName(parameters: ParameterType): ReturnType {
    // Function body
}
Kotlin

fun String.addExclamation(): String {
    return "$this!"
}

val originalString = "Hello"
val modifiedString = originalString.addExclamation() // "Hello!"
Kotlin

2. Nullable Receiver Type:

Extension functions can also be called on nullable types. The receiver type can be nullable, and you can use the safe call operator ?. within the function body.

Example:

fun String?.safeUpperCase(): String {
    return this?.toUpperCase() ?: "String is null"
}

val nullableString: String? = "hello"
val result = nullableString.safeUpperCase() // "HELLO"

val nullString: String? = null
val result2 = nullString.safeUpperCase() // "String is null"
Kotlin

3. Extension Properties:

In addition to functions, Kotlin allows you to define extension properties. These are handy for adding properties to classes without declaring them in the class body.

val String.hasSpaces: Boolean
    get() = this.contains(" ")

val hasSpaces = "Hello World".hasSpaces // true
Kotlin

4. Scoping of Extensions:

  • Extensions do not modify the classes they extend.
  • They can be defined outside of the class and even outside the class’s file.
  • Extensions are resolved statically, based on the type they are called on at compile time.

5. Kotlin Extension Function with Using Extensions for DSLs (Domain-Specific Languages):

Extensions can be powerful tools for creating fluent DSLs, allowing you to enhance the readability and conciseness of your code in specific domains.

A Domain-Specific Language (DSL) is a programming language or specification language dedicated to a particular problem domain, a particular problem representation technique, and/or a particular solution technique. In simpler terms, it’s a specialized language or syntax tailored to solve specific types of problems within a particular field or industry.

class Request {
    fun method(method: String) { /* ... */ }
    fun path(path: String) { /* ... */ }
}

fun request(block: Request.() -> Unit): Request {
    val request = Request()
    request.block()
    return request
}

val req = request {
    method("GET")
    path("/user")
}
Kotlin

In this DSL example, the request function takes a lambda with Request as its receiver type, enabling a clean and readable syntax for constructing requests.

Kotlin’s extension functions provide a flexible way to enhance existing classes and create expressive and concise APIs. By judiciously using extensions, you can make your codebase more readable and maintainable.

Here is a list of some common use cases and examples of extension functions in Kotlin:

Extension FunctionsDescription
String.capitalizeWords()Capitalizes the first letter of each word in a string.
String.isEmailValid()Checks if a string represents a valid email address.
List<T>.second()Returns the second element of a list (if available).
List<T>.filterNotNull()Filters out null elements from a list.
Collection<T>.average()Calculates the average of numeric elements in a collection.
Collection<T>.randomElement()Returns a random element from a collection.
Date.format(pattern: String)Formats a Date object as a string based on a specified pattern.
View.isVisible()Checks if a View is visible (Android specific).
View.hide()Sets the visibility of a View to View.GONE (Android specific).
Int.isEven()Checks if an integer is even.
Int.isOdd()Checks if an integer is odd.
File.deleteRecursive()Deletes a file or directory and its contents recursively.
SharedPreferences.getStringOrNull(key: String)Retrieves a string value from SharedPreferences with a fallback to null (Android specific).
Fragment.showToast(message: String)Shows a toast message from a fragment (Android specific).
RecyclerView.scrollToEnd()Scrolls a RecyclerView to the end of its data (Android specific).

Let’s say you frequently perform view animations in your Android app. You can create an extension function to simplify the process of animating a view’s translation:

// Extension function for View to animate translation
fun View.animateTranslation(translationX: Float, translationY: Float, duration: Long = 300) {
    animate()
        .translationX(translationX)
        .translationY(translationY)
        .setDuration(duration)
        .start()
}
Kotlin

Explanation:

  • This extension function is defined for the View class.
  • It takes three parameters: translationX and translationY represent the translation values in the x and y directions, and duration is an optional parameter for animation duration (default is 300 milliseconds).
  • Inside the function, animate() is called on the view, and various animation properties are set using methods like translationX, translationY, and setDuration.
  • Finally, the animation is started with start().

Now, you can easily animate a view’s translation in your code:

// Example of using the extension function
val myView: View = // obtain View instance

// Animate the view's translation
myView.animateTranslation(100f, 150f, 500)
Kotlin

This extension function abstracts away the complexity of setting up translation animations, making your code more readable.

Kotlin Functions

Advanced Functions Higher-Order Functions – Lambda Functions – Extension Functions – Infix Functions- Generic Functions
See More Info

Functions– Simple Functions – Function Parameters – Function Return Types – Function Scope
See More Info

Functional Programming FunctionsImmutability and Pure Functions- Function Composition – Functional Operators
See More Info

Feel free to follow and join my email list at no cost. Don’t miss out — sign up now!

Please check out my earlier blog post for more insights. Happy reading!

The Innovative Fundamentals of Android App Development in 2023

How to learn Android App Development in 2023 – Full Guide For Beginners using Kotlin Language

What is the Repository Pattern in Android? A Comprehensive Guide

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x