2
2
.
.
4
4
.
.
6
6
E
E
x
x
t
t
e
e
n
n
s
s
i
i
o
o
n
n
s
s
I
I
n
n
f
f
o
o
[
[
R
R
]
]
Extensions allow you to add Properties and Methods to an existing Class.
Extension is declared by simply placing Class name before the Field/Property/Method name Person.sayHello().
Unfortunately Extension Property
must be declared inside Class Scope (can't be added inside a Method)
can't have Backing Field so you can't use Keyword field inside it (use Backing Properties to store data)
Extension Properties & Methods
//===========================================================================================================
// CLASS: Person
//===========================================================================================================
class Person {
//DECLARE PROPERTIES.
var name : String = ""
//CONSTRUCTOR.
constructor(name: String) { this.name = name }
}
//===========================================================================================================
// CLASS: Soldier
//===========================================================================================================
class Soldier {
//ADD EXTENSION PROPERTY.
val Person.greet : String
get() { return "Hello $name" } //REFERENCE name FROM EXTENDED CLASS.
//ADD EXTENSION METHOD.
fun Person.sayHello () {
print("Hello $name") //REFERENCE name FROM EXTENDED CLASS.
}
//TEST METHOD.
fun test() {
var john = Person("John")
println(john.greet) //CALL EXTENSION PROPERTY.
john.sayHello() //CALL EXTENSION METHOD.
}
}
//===========================================================================================================
// FUNCTION: main
//===========================================================================================================
fun main() {
var soldier = Soldier()
soldier.test()
}
N
N
o
o
t
t
e
e
s
s
[
[
R
R
]
]
Extensions are useful if you don't have access to third party Class but you want it to have additional Properties & Methods
At the same time you don't want to create an additional Class that Inherits from that third party Class in order to add
additional Properties & Methods that way (and then to work with this Class instead directly with third party Class).
Extensions do not modify classes they extend - they do not insert new members into a class.
They just make new members callable with the dot-notation on instances of this class.
Since extensions do can't insert members into classes, there’s no way to have a backing field because you cannot add a
field to an existing class. This is why initializers are not allowed for extension properties.