0
0
Kotlinprogramming~10 mins

Explicit type declaration in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Explicit type declaration
Start
Declare variable with type
Assign value matching type
Use variable
End
This flow shows declaring a variable with a specific type, assigning a matching value, then using it.
Execution Sample
Kotlin
var name: String
name = "Alice"
var age: Int
age = 30
println("Name: $name, Age: $age")
Declares variables with explicit types and prints their values.
Execution Table
StepActionVariableTypeValueOutput
1Declare 'name' with type StringnameStringuninitialized
2Assign "Alice" to 'name'nameString"Alice"
3Declare 'age' with type IntageIntuninitialized
4Assign 30 to 'age'ageInt30
5Print valuesName: Alice, Age: 30
💡 Program ends after printing the output.
Variable Tracker
VariableStartAfter Step 2After Step 4Final
nameuninitialized"Alice""Alice""Alice"
ageuninitializeduninitialized3030
Key Moments - 2 Insights
Why do we write ': String' or ': Int' after variable names?
This tells Kotlin the exact type the variable must hold, so it only accepts matching values. See steps 1 and 3 in the execution table.
What happens if we assign a value of the wrong type?
Kotlin will give an error because the value does not match the declared type. This is why in steps 2 and 4, the assigned values match the declared types.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'name' after step 2?
Auninitialized
B"Alice"
C30
Dnull
💡 Hint
Check the 'Value' column for 'name' at step 2 in the execution table.
At which step is the variable 'age' assigned a value?
AStep 1
BStep 2
CStep 4
DStep 5
💡 Hint
Look for the assignment action for 'age' in the execution table.
If we remove ': Int' from 'age' declaration, what changes in the execution?
AKotlin infers the type automatically
BThe program will not compile
CThe variable 'age' becomes a String
DThe variable 'age' can hold any type
💡 Hint
Kotlin can infer types if explicit declaration is missing, so no error occurs.
Concept Snapshot
Explicit type declaration in Kotlin:
val variableName: Type = value
var variableName: Type = value
- Declares variable with fixed type
- Helps catch type errors early
- Value must match declared type
Full Transcript
This example shows how to declare variables in Kotlin with explicit types. First, we declare 'name' as a String and assign "Alice" to it. Then, we declare 'age' as an Int and assign 30. Finally, we print both values. Explicit type declaration means telling Kotlin exactly what type a variable holds, so it only accepts matching values. This helps avoid mistakes. The execution table shows each step: declaration, assignment, and printing. The variable tracker shows how values change. Remember, if you assign a wrong type, Kotlin will give an error. You can also let Kotlin guess the type by skipping explicit declaration, but here we show how to write it clearly.