Hoinzey

Javascript. Kotlin. Android. Java

Kotlin: Extension functions

Extension functions allow us to extend the functionality of a class without having to inherit from them or change the class itself. This is useful if you want to add a custom method to String for example but its also useful to keep your Model objects neat and only keep the minimum amount of logic in them as needed.


The syntax is to put the name of the Class or Interface you are extending, followed by a dot, and the name of the method you are adding. The class is the receiver type and the function is the receiver object


The example below shows us extending the functionality of ElectronicProduct within the CheckoutHelper class. This function could easily have been represented as a standard function which just takes the Product as a parameter, but hey you sit there and try come up with amazing original ideas.


CheckoutHelper
ElectronicProduct
                    
    class CheckoutHelper {

        fun calculatePrice(products: List): Int {
            var total = 0
            for(product in products) {
                total += if(product.isOnSale()) {
                    product.price / 2
                } else product.price
            }
            return total
        }
    
        fun ElectronicProduct.isOnSale(): Boolean {
            return productRef.startsWith("SAM")
                    && percentInStock <= 15
        }
    }
                                        
                    
    data class ElectronicProduct(
        var productId: Int = 0,
        var name: String,
        var productRef: String,
        var price: Int,
        var percentInStock: Int)
                                        

Note that extension functions don't allow you to break encapsulation. You can't access private or protected members of the class.