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.
val variableName: Type = value var variableName: Type = value
val age: Int = 25
var name: String = "Alice"
val price: Double = 19.99
var isActive: Boolean = true
fun main() { val year: Int = 2024 var greeting: String = "Hello" println("Year: $year") println("Greeting: $greeting") greeting = "Hi" println("New Greeting: $greeting") }
val or var followed by variable name, colon, type, then assignment.var age: Int = 25. Others have syntax errors.val number: Int = 10 var text: String = "Hello" text = "Hi" println(number) println(text)
number is a val (fixed) with value 10. text is a var (changeable) initially "Hello", then changed to "Hi".number outputs 10. Printing text outputs the updated value "Hi".val count: Int = 5 count = 10
val means the variable is read-only and cannot be reassigned after initialization.count which is declared as val, causing an error.score that can change and must hold decimal numbers. Which explicit type declaration is correct in Kotlin?score must be changeable, so use var, not val.Double or Float, but value 95.5 is a Double by default.var and Double with correct value. Others either use val, wrong type, or wrong value type.Pass the test and this pattern moves unknown