object declaration - it is an object with a name. You use the object name to access its function and properties. This is not a one time use. You are not allowed to use this in an expression.
syntax:
object Name {
//statement
}
===============
fun main(){
YourObject.prop1 = "Bell Cranel"
YourObject.displaySomething()
}
object YourObject{
var prop1 = "Your name"
fun displaySomething() = println("I am $prop1")
}
===============
Result:
I am Bell Cranel
Note:
1. You are allowed to extend a Mother class or implement an interface
2. When inside the class, the object can be declared as a companion of the class. You have an option to use an object name or not. If you decided not to name the companion object, during invocation, you can just use the Companion keyword as a name.
3. Object declaration is not allowed within a function or a method.
==================
fun main(){
YourClass.name = "Bucks"
YourClass.displaySomething()
YourClass.SecondObject.name = "Nets"
YourClass.SecondObject.displaySomething()
}
class YourClass{
private val prop1 = "First Property"
companion object FirstObject{
var name = "First"
fun displaySomething() = println("$name: I cannot access the first property!")
}
object SecondObject{
var name = "Second"
fun displaySomething() = println("$name: Same here too!")
}
}
==================
Result:
Bucks: I cannot access the first property!
Nets: Same here too!
Note:
1. Object expression is initialized and executed immediately.
2. Object declaration is initialized lazily.
3. Companion objects will be initialized after the class is loaded.
YOU ARE READING
Kotlin Programming
RandomI have been trying to learn things online. I will put my notes in here. I put things in my own words and i do not copy their programs. I try to do things the right way so that i may learn. Below is the site where i study. Go check this out if you wa...
