Extension Functions

 Kotlin provides a convenient syntax for declaring extension functions. These allow you to add functions to an existing class without having access to its source code.


Extensions do not actualy modify the classes they extend.

By defining an extension, you do not insert new members into the class.

Extension functions are defined outside of the class they extend, so, they don't have access to private variables. 


You can also define extension properties

// File:            Main.kt
// Programmer: Engineer Nolverto Urias Obeso
// Creation Date: 06/23/2023
// Email: nolvertou@gmail.com
// Description: Using extension functions and properties

fun main() {
println("Does it have spaces".hasSpaces()) // Output: true

val aquariumPlant = AquariumPlant("Green", 100)
println(aquariumPlant.isRed()) // Output: false

val aquariumPlant2 = AquariumPlant("Red", 2)
println(aquariumPlant2.isRed()) // Output: true
// println(aquariumPlant.isBig()) // ERROR: Cannot access 'size': it is private in 'AquariumPlant'

aquariumPlant.print() // Output: AquariumPlant

val greenLeafyPlant = GreenLeafyPlant(20)
greenLeafyPlant.print() // Output: GreenLeafyPlant
println(aquariumPlant.isGreen) // Output: true

}

// Extension function
fun String.hasSpaces(): Boolean{
val found: Char? = this.find{it == ' '}
return found != null
}

open class AquariumPlant(val color: String, private val size: Int)
// Extension functions
fun AquariumPlant.isRed() = color == "Red"
//fun AquariumPlant.isBig() = size > 50

class GreenLeafyPlant(size: Int): AquariumPlant("Green", size)
// Extension functions
fun AquariumPlant.print() = println("AquariumPlant")
fun GreenLeafyPlant.print() = println("GreenLeafyPlant")

// Extension Property
val AquariumPlant.isGreen: Boolean
get() = color == "Green"

Comments

Popular posts from this blog