Val vs Var
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 5 of 93.
In Kotlin, you use val and var to store values.
var creates a variable. Its value can be changed later:
fun main() {
var score = 10
println(score) // 10
score = 20
println(score) // 20
}val creates a read-only value. The name cannot be reassigned once initialized. This does not make an object referenced by it deeply immutable:
fun main() {
val name = "Alice"
println(name) // Alice
// name = "Bob" // ❌ Error! Val cannot be reassigned
}When to use which?
- Use
valby default. If a value doesn't need to change, make it read-only. - Use
varonly when you know the value will need to change.
Challenge
BeginnerCreate a read-only value called language with the value "Kotlin" and a variable called age with the value 25. Print both values on separate lines.
Try it yourself
fun main() {
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground