In Kotlin, you create a class with the class keyword, and you create an object instance by calling the class constructor.
class Person {
var name: String = "Unknown"
var age: Int = 0
}
fun main() {
val person = Person()
person.name = "Alice"
person.age = 25
println("${person.name} is ${person.age} years old")
}
Output:
Alice is 25 years old
Class with a constructor
A more common Kotlin style is to define properties directly in the constructor:
class Person(
val name: String,
var age: Int
)
fun main() {
val person = Person("Alice", 25)
println("${person.name} is ${person.age} years old")
}
Here:
class Person(...)defines a class.val nameis a read-only property.var ageis a mutable property.Person("Alice", 25)creates an object of the class.
Kotlin object keyword
Kotlin also has the object keyword, which creates a singleton object:
object AppConfig {
val appName = "My Kotlin App"
val version = "1.0"
}
fun main() {
println(AppConfig.appName)
println(AppConfig.version)
}
Unlike a class, you do not create instances of an object. There is only one instance, and you access it directly by name.
