fun String.hasSpaces(): Boolean {
val found = this.find { it == ' '}
return found != null
}
// OR
fun String.hasSpaces() = find{ it == ' '} != null
// true
fun extensionsExample() {
"Does it have spaces?".hasSpaces()
}
// they are defined outside the class they extend (they don't have access to private variables)
class AquariumPlant(val color: String, private val size: Int)
fun AquariumPlant.isRed() = color == "Red"
//
fun GreanLeafyPlant.print() = println("GreenLeafyPlant")
fun AquariumPlant.print() = println("AquariumPlant")
fun staticExample() {
val plant = GreenLeafyPlant(size = 50)
plant.print() // GreenLeafyPlant
val aquariumPlant: AquariumPlant = plant
aquariumPlant.print() // AquariumPlant
}
// Extension properties
class AquariumPlant(val color: String, print val size: Int)
val AquariumPlant.isGreen: Boolean
get() = color == "green"
// Property Example
fun propertyExample() {
val plant = AquariumPlant("Green", 50)
plant.isGreen // true
}