2
2
.
.
4
4
.
.
4
4
P
P
r
r
o
o
p
p
e
e
r
r
t
t
i
i
e
e
s
s
I
I
n
n
f
f
o
o
Property is a named pair of get() and set() Methods which are accessed using Field Syntax
name = "John" actually calls name.set("John")
result = name actually calls name.get("John")
This means that Property doesn't need to store any Value. Its Methods can simply call other Fields, Properties and
Methods. Therefore both get() and set() Methods can store multiple Values into multiple other Fields or Properties.
And get() Method can return value which is just a combination of different other Fields, Properties and Methods.
But if needed Property can have a so called Backing Field to store a single Value.
Backing Field is referenced from get() and set() Methods using field Keyword.
Backing Field is not visible in the Kotlin Code. Instead it is added to a generated Java Code.
Both get() and set() Methods are optional. If none is defined we get a Field.
But in Java generated code, Kotlin might add default get() and set() Methods implementing Field as a Property.
Use this to reference Properties from within Class (Fields, Properties, Methods).
Properties can also be
public Properties can be referenced inside & outside of the Class or Object (by default)
private Properties can be referenced only inside the Class or Object (from Fields, Properties, Methods)
Properties
//===========================================================================================================
// CLASS: Person
//===========================================================================================================
class Person {
//DECLARE PROPERTY.
public var name : String = "" //Data Type returned by get() & input into set(value).
get() { return "Hello $field" } //Optional
set(value) { field = value } //Optional
//CONSTRUCTOR.
constructor(name: String) { this.name = name } //Use this to reference Property
}
//===========================================================================================================
// FUNCTION: main
//===========================================================================================================
fun main() {
//CREATE OBJECT.
var john = Person("John")
john.name = "Bill" //name.set("Bill")
var greet = john.name //name.get()
//DISPLAY.
print(greet) //Hello Bill
}