As we build upon our programs, we’ll often need to update the values of variables following certain calculations. Assume a program that increases the current speed of a vehicle to match a speed limit of 55:

var currentSpeed = 45 currentSpeed = currentSpeed + 10 print(currentSpeed) // Prints: 55

In order to increase and update the value of currentSpeed, we’ve added 10 to currentSpeed and reassigned it back to currentSpeed. Kotlin provides an even shorter syntax for operations like this with augmented assignment operators.

Augmented assignment operators execute a calculation and reassign its result to a variable all in one step. Each consists of an arithmetic operator immediately followed by the = operator. Take a look at the difference in syntaxes:

Long Syntax:

a = a + b

Short Syntax with an Augmented Assignment Operator:

a += b 

Here’s a breakdown of each:

Operation Long Syntax Short Syntax
Add a = a + b a += b
Subtract a = a - b a -= b
Multiply a = a * b a *= b
Divide a = a / b a /= b
Mod a = a % b a %= b

Keeping the short syntax in mind, we can now refactor and optimize our previous program to its final, concise state:

currentSpeed += 10 println(currentSpeed) // Prints: 55




In NumberFacts.kt, we’ve declared several variables and initialized them with numerical values that are erroneous. Use the following instructions to update each variable with its correct value using Kotlin’s augmented assignment operators:

  • speedOfLight: add 282 and reassign the new value
  • perfectSquare: multiply by 2 and reassign the new value
  • sheldonsFavoriteNum: divide by 3 and reassign the new value
  • emergency: subtract 9 and reassign the new value
  • firstCountingNum: use modulo to divide by 5 and reassign the remainder

Run your program to see the correct numerical values and facts.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?