Skip to content

Latest commit

 

History

History
executable file
·
44 lines (31 loc) · 1.93 KB

03_extensionFunctions.md

File metadata and controls

executable file
·
44 lines (31 loc) · 1.93 KB

Extension Functions and Properties

Kotlin lets you add new members to any class with the extensions mechanism. Namely, there are two types of extensions: extension functions and extension properties. They look a lot like normal functions and properties but with one important difference: you need to specify the type that you extend.

data class Item(val name: String, val price: Float)                                         // 1  

data class Order(val items: Collection<Item>)  

fun Order.maxPricedItemValue(): Float = this.items.maxByOrNull { it.price }?.price ?: 0F    // 2  
fun Order.maxPricedItemName() = this.items.maxByOrNull { it.price }?.name ?: "NO_PRODUCTS"

val Order.commaDelimitedItemNames: String                                                   // 3
    get() = items.map { it.name }.joinToString()

fun main() {

    val order = Order(listOf(Item("Bread", 25.0F), Item("Wine", 29.0F), Item("Water", 12.0F)))
    
    println("Max priced item name: ${order.maxPricedItemName()}")                           // 4
    println("Max priced item value: ${order.maxPricedItemValue()}")
    println("Items: ${order.commaDelimitedItemNames}")                                      // 5

}
  1. Defines simple models of Item and Order. Order can contain a collection of Item objects.
  2. Adds extension functions for the Order type.
  3. Adds an extension property for the Order type.
  4. Calls extension functions directly on an instance of Order.
  5. Accesses the extension property on an instance of Order.

It is even possible to execute extensions on null references. In an extension function, you can check the object for null and use the result in your code:

//sampleStart
fun <T> T?.nullSafeToString() = this?.toString() ?: "NULL"  // 1

fun main() {
    println(null.nullSafeToString())
    println("Kotlin".nullSafeToString())
}
//sampleEnd