0
0
Kotlinprogramming~5 mins

Creating instances without new keyword in Kotlin

Choose your learning style9 modes available
Introduction

In Kotlin, you create objects without using the new keyword. This makes the code simpler and easier to read.

When you want to create a new object of a class in Kotlin.
When you are learning Kotlin and want to understand how object creation differs from other languages like Java.
When you want to write clean and concise code without extra keywords.
When you need to quickly create instances for data handling or logic in your app.
Syntax
Kotlin
val instance = ClassName(arguments)

You just call the class name like a function to create an instance.

No need for new keyword as in some other languages.

Examples
This creates a new Person object with name "Alice" and age 30.
Kotlin
val person = Person("Alice", 30)
This creates a new empty mutable list of integers.
Kotlin
val list = mutableListOf<Int>()
This creates a Rectangle object with width 5.0 and height 10.0.
Kotlin
val rectangle = Rectangle(5.0, 10.0)
Sample Program

This program creates a Person instance without using new. It then prints the person's name and age.

Kotlin
class Person(val name: String, val age: Int)

fun main() {
    val person = Person("Bob", 25)
    println("Name: ${person.name}, Age: ${person.age}")
}
OutputSuccess
Important Notes

Kotlin simplifies object creation by removing the need for new.

Just call the class constructor like a function with parentheses and arguments.

This makes Kotlin code cleaner and easier to write.

Summary

Kotlin creates instances by calling the class name like a function.

No new keyword is needed.

This leads to simpler and more readable code.