How do I create a class and an object in Kotlin?

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 name is a read-only property.
  • var age is 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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.