Augmented Assignment
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 21 of 93.
When you need to update a variable's value based on its current value, Kotlin provides augmented assignment operators. These combine an arithmetic operation with assignment into a single, shorter expression.
Instead of writing x = x + 5, you can write x += 5. Both do the same thing, but the augmented version is cleaner and more common in real code:
fun main() {
var score = 10
score += 5 // Same as: score = score + 5
println(score) // Prints: 15
}Each arithmetic operator has an augmented assignment version:
| Operator | Example | Equivalent To |
|---|---|---|
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
%= | x %= 3 | x = x % 3 |
fun main() {
var balance = 100
balance -= 25 // Subtract 25
balance *= 2 // Double it
println(balance) // Prints: 150
}Remember, these operators modify the variable, so you must use var, not val.
Challenge
EasyWrite a function applyOperations that takes start, addValue, and multiplyValue and returns the final result after applying augmented assignment operations.
Starting with the initial value, first add addValue to it, then multiply the result by multiplyValue.
Logic:
- Start with the
startvalue - Use
+=to addaddValue - Use
*=to multiply bymultiplyValue
Parameters:
start(Int): The initial valueaddValue(Int): The value to addmultiplyValue(Int): The value to multiply by
Returns: The final result after both operations (Int)
Try it yourself
fun applyOperations(start: Int, addValue: Int, multiplyValue: Int): Int {
// Write code here
}
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