0
0
KotlinHow-ToBeginner · 3 min read

How to Create Object in Kotlin: Syntax and Examples

In Kotlin, you create an object by defining a class and then instantiating it using the ClassName() syntax. Alternatively, you can create a singleton object using the object keyword without needing to instantiate it.
📐

Syntax

To create an object in Kotlin, you first define a class. Then you create an instance of that class using parentheses. For singletons, use the object keyword to create an object directly.

  • Class definition: class ClassName { ... }
  • Create instance: val obj = ClassName()
  • Singleton object: object SingletonName { ... }
kotlin
class Person(val name: String) {
    fun greet() {
        println("Hello, my name is $name")
    }
}

val person = Person("Alice")
💻

Example

This example shows how to create a class, instantiate an object, and call its method. It also shows how to create a singleton object and use its function.

kotlin
class Person(val name: String) {
    fun greet() {
        println("Hello, my name is $name")
    }
}

val person = Person("Alice")
person.greet()

object Logger {
    fun log(message: String) {
        println("Log: $message")
    }
}

Logger.log("This is a log message")
Output
Hello, my name is Alice Log: This is a log message
⚠️

Common Pitfalls

One common mistake is forgetting to use parentheses when creating an instance of a class. Another is trying to instantiate an object declared with the object keyword, which is a singleton and does not need instantiation.

kotlin
/* Wrong: Missing parentheses */
// val person = Person  // Error: This does not create an object

/* Correct: Use parentheses */
val person = Person("Bob")

/* Wrong: Trying to instantiate an object singleton */
// val logger = Logger()  // Error: Cannot call constructor

/* Correct: Use the object directly */
Logger.log("Working correctly")
📊

Quick Reference

ConceptSyntaxDescription
Class Definitionclass ClassName { ... }Defines a blueprint for objects
Create Instanceval obj = ClassName()Creates an object from a class
Singleton Objectobject ObjectName { ... }Creates a single instance object
Access SingletonObjectName.method()Use singleton without instantiation

Key Takeaways

Create objects by defining a class and calling ClassName() with parentheses.
Use the object keyword to create singleton objects without instantiation.
Always include parentheses when creating class instances to avoid errors.
Singleton objects cannot be instantiated; use them directly by name.
Classes can have properties and functions accessed through their objects.