0
0
Kotlinprogramming~10 mins

Creating instances without new keyword in Kotlin - Visual Walkthrough

Choose your learning style9 modes available
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.
Execution Sample
Kotlin
class Person(val name: String)

fun main() {
    val p = Person("Anna")
    println(p.name)
}
This code creates a Person instance named Anna without using 'new' and prints the name.
Execution Table
StepActionCode LineResult
1Define class Person with property nameclass Person(val name: String)Class Person ready
2Call Person constructor with "Anna"val p = Person("Anna")Instance p created with name = "Anna"
3Print p.nameprintln(p.name)Output: Anna
4Program ends}Execution complete
💡 Reached end of main function, program stops
Variable Tracker
VariableStartAfter Step 2Final
pnullPerson(name="Anna")Person(name="Anna")
Key Moments - 2 Insights
Why don't we use 'new' to create an instance in Kotlin?
Kotlin simplifies instance creation by calling the class name directly as a function, as shown in step 2 of the execution_table.
How does Kotlin know to create an instance when we write Person("Anna")?
Person("Anna") calls the primary constructor of the class Person, which creates the instance, as seen in step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of variable 'p' after step 2?
Anull
BPerson instance with name "Anna"
CString "Anna"
DUndefined
💡 Hint
Check variable_tracker row for 'p' after step 2
At which step does the program print the output?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Action' and 'Result' columns in execution_table
If we change the code to val p = Person("Bob"), what changes in the execution_table?
AStep 1 changes
BStep 3 output remains "Anna"
CStep 2 result changes to name = "Bob"
DNo changes at all
💡 Hint
Focus on the 'Result' column in step 2 and step 3 of execution_table
Concept Snapshot
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.
Full Transcript
In Kotlin, you create an instance of a class by calling the class name with parentheses and arguments, without using the 'new' keyword. For example, val p = Person("Anna") creates a new Person object with the name Anna. The program then can use this instance, like printing p.name. This is simpler than some other languages that require 'new'. The execution steps show defining the class, creating the instance, printing the name, and ending the program. The variable tracker shows how 'p' changes from null to the new Person instance. This method is clear and concise for beginners.