0
0
Kotlinprogramming~5 mins

Explicit type declaration in Kotlin

Choose your learning style9 modes available
Introduction
Explicit type declaration helps you tell the computer exactly what kind of data you want to store. It makes your code clear and helps avoid mistakes.
When you want to make your code easier to read for others.
When the computer cannot guess the type by itself.
When you want to be sure a variable holds only a specific type of data.
When you want to avoid accidental changes to the variable type later.
When you want to catch errors early during coding.
Syntax
Kotlin
val variableName: Type = value
var variableName: Type = value
Use val for values that do not change (like constants).
Use var for variables that can change later.
Examples
Declares a constant integer named age with value 25.
Kotlin
val age: Int = 25
Declares a variable string named name with value "Alice".
Kotlin
var name: String = "Alice"
Declares a constant double (decimal number) named price with value 19.99.
Kotlin
val price: Double = 19.99
Declares a variable boolean named isActive with value true.
Kotlin
var isActive: Boolean = true
Sample Program
This program shows how to declare variables with explicit types. It prints the values and changes the variable greeting.
Kotlin
fun main() {
    val year: Int = 2024
    var greeting: String = "Hello"
    println("Year: $year")
    println("Greeting: $greeting")
    greeting = "Hi"
    println("New Greeting: $greeting")
}
OutputSuccess
Important Notes
Explicit types make your code easier to understand for others and for yourself later.
If you do not specify a type, Kotlin tries to guess it from the value.
Use explicit types when the guess might be unclear or when you want to be very clear.
Summary
Explicit type declaration tells Kotlin exactly what type a variable or value has.
Use val for fixed values and var for changeable variables.
It helps prevent mistakes and makes your code easier to read.