Kotlin Object represents a single static instance of its Properties and Methods.
Kotlin Object is like a Class that only has static Properties and Methods and from which you can't create Instances.
Since you can't create Instances it doesn't have Constructor and you can't create it using Parameters.
Constructor isn't needed since when you create it you immediately set all the Properties to wanted Values.
Kotlin Objects are useful when you don't need multiple instances of the same Class.
They are similar to Closures since they are also used when we don't need to call the same Function multiple times.
Properties and Methods are public by default but you can declare them as private.
Object can extend single Class and Implement multiple Interfaces.
Object is declared by
● using Keyword object object
● followed by the Object Name Person
● followed by the Object Body { ... }
○ which can have Properties val age = 20 (Variables, Constants, Enumerators,...)
○ which can have Methods fun greet() { ... }
Basic Object Syntax
object Person { ... }
Basic Object Syntax
//===========================================================================================================
// OBJECT: Person
//===========================================================================================================
object Person {
val age = 20
fun greet(name: String) = "$name is $age years old"
}
//===========================================================================================================
// FUNCTION: main
//===========================================================================================================
fun main() {
var result = Person.greet("John")
println(result)
}