Concept Flow - Creating instances without new keyword
Class Definition
Call Constructor
Instance Created
Use Instance
In Kotlin, you create an instance by calling the class name like a function, without using the 'new' keyword.
class Person(val name: String) fun main() { val p = Person("Anna") println(p.name) }
| Step | Action | Code Line | Result |
|---|---|---|---|
| 1 | Define class Person with property name | class Person(val name: String) | Class Person ready |
| 2 | Call Person constructor with "Anna" | val p = Person("Anna") | Instance p created with name = "Anna" |
| 3 | Print p.name | println(p.name) | Output: Anna |
| 4 | Program ends | } | Execution complete |
| Variable | Start | After Step 2 | Final |
|---|---|---|---|
| p | null | Person(name="Anna") | Person(name="Anna") |
Kotlin creates instances by calling the class name like a function. No 'new' keyword is needed. Syntax: val obj = ClassName(args) This calls the constructor and returns the instance. Use instance properties or methods with dot notation.
Car without using the new keyword?new keyword; instead, it calls the class name like a function.Car, simply write Car() without new.Person in Kotlin?val p = Person() matches Kotlin's syntax for creating an instance.class Dog(val name: String) {
fun bark() = "Woof! I am $name"
}
fun main() {
val dog = Dog("Buddy")
println(dog.bark())
}dog is created by calling Dog("Buddy"), setting name to "Buddy".bark() function returns the string with $name replaced by "Buddy".class Book(val title: String)
fun main() {
val b = new Book("Kotlin Basics")
println(b.title)
}new Book("Kotlin Basics"), but Kotlin does not use the new keyword.Book("Kotlin Basics") without new.Person instances without using the new keyword?class Person(val name: String, val age: Int)
listOf() accepts instances created by Person("Alice", 30) and Person("Bob", 25).Pass the test and this pattern moves unknown