KotLin For Loop
KotLin For Loop
Course Menu
Workspace restored.
Get Unstuck
Tools
Learn
LOOPS
for Loop
When we know how many times we want a section of code to repeat, we often use a for loop.
A for loop starts with the for keyword and is followed by a statement that defines a loop variable
followed by identifying an iterator:
for(i in 1..4) {
println("I am in a loop!")
}
An iterator is an object that allows us to step through and access every individual element in a
collection of values. In most cases, the iterators we use in for loops are ranges and collections. In
this example, the range has 4 elements so the for loop repeats 4 times:
I am in a loop!
I am in a loop!
I am in a loop!
I am in a loop!
It is important to note that the loop variable only exists within the loop’s code block. Trying to
access the loop variable outside the for loop will result in an error.
Here is an example of using the loop variable within the loop body:
for (i in 1..4) {
println("i = $i")
}
While the above example uses literal numbers 1..4 to define the range, we can also use variables
to define the boundaries of our loop’s range, giving us more dynamic control over our loop’s
iteration:
i = 1
i = 2
i = 3
i = 4
Instructions
1.
Create a for loop that outputs "Hello, Codey!" five times.
Hint
With i as the loop variable and 1..5 as the iterator, create a for loop with println("Hello,
Codey!") as the loop body.
Now instead of just outputting text, it’s time to use the loop variable i in the loop body.
Add another println() with a string template directly below the first println() so the loop
creates the following output:
Hello, ilias!
i = 1
Hello, ilias!
i = 2
Hello, ilias!
i = 3
Hello, ilias!
i = 4
Hello, ilias!
i = 5
Checkpoint 3 Passed
Hint
Add a println() statement to the loop body with the string template "i = $i".
Concept Review
Helloilias.kt
fun main() {
for(i in 1..5){
println("Hello, ilias!")
println("i = $i")
Ouput:
My Home
Course Menu
Workspace restored.
Get Unstuck
Tools
Learn
LOOPS
Controlling the Iteration
Sometimes we want to count backwards, or count by 2s, or both! Using certain functions
alongside or instead of the normal range operator (..) can enhance the iterative abilities of
our for loops. The functions downTo, until and step give us more control of a range and therefore
more control of our loops.
The downTo function simply creates a reverse order group of values, where the starting boundary
is greater than the ending boundary. To accomplish this, replace the range operator (..)
with downTo:
for (i in 4 downTo 1) {
println("i = $i")
}
We can see in the output that the first number in i is 4 and the last is 1:
i = 4
i = 3
i = 2
i = 1
The until function creates an ascending range, just like the (..) operator, but excludes the upper
boundary:
for (i in 1 until 4) {
println("i = $i")
}
The upper boundary, 4, is not included in the output:
i = 1
i = 2
i = 3
Up until now, each of these functions, including the range operator (..), have counted up or
down by one. The step function specifies the amount these functions count by:
i = 1
i = 3
i = 5
i = 7
Instructions
1.
Let’s look at how we can change the behavior of ranges in for loops by implementing a loop that
counts backwards.
Hint
Create a for loop with i as the loop variable and 10 downTo 1 as the iterator. The loop body
should have a println() that outputs "i = $i".
Hint
Create a for loop with j as the loop variable and 1 until 10 as the iterator. The loop body
has println() that outputs "j = $j".
Run the code and you will see that the new loop does not output the iterator’s upper boundary 10.
Counting up by 2 from 1 does not include 10.
Checkpoint 4 Passed
Hint
Create a for loop with k as the loop variable and 1..10 step 2 as the iterator. The loop body
has println() that outputs "k = $k".
ranges.kt
fun main() {
for (i in 10 downTo 1) {
println("i = $i")
println("j = $j")
println("k = $k")
Output:
LOOPS
Iterating Through Collections
Instead of using a range, we can use the structure of a collection as an iterator.
A for loop will iterate through each of the collection’s elements with the loop
variable holding the value of the current element. We will focus on lists and
sets in this exercise and maps in the next one.
I have apples.
I have oranges.
I have bananas.
When we first learned about lists and sets in the collections lesson, we
discussed their commonality as well as their differences. An additional
similarity is that the syntax for iterating through a list and a set is the same.
Instructions
1.
Now you’ll use collections as iterators. To start, implement a for loop using the
list mySchedule. The loop should contain:
Hint
Create a for loop with task as the loop variable and mySchedule as the iterator.
The loop body should use println() to output the loop variable.
Hint
Destructure the loop variables taskIndex and task and
use myTasks.withIndex() as the iterator. The loop body should use println() to
output the string template "$taskIndex: $task".
fun main() {
val mySchedule = listOf("Eat Breakfast", "Clean Up", "Work", "Eat Lunch", "Clean Up", "Work", "Eat
Dinner", "Clean Up")
val myTasks = setOf("Eat Breakfast", "Clean Up", "Work", "Eat Lunch", "Clean Up", "Work", "Eat
Dinner", "Clean Up")
println("-- mySchedule Output --")
Soluations:
fun main() {
val mySchedule = listOf("Eat Breakfast", "Clean Up", "Work", "Eat Lunch", "Clean Up", "Work", "Eat
Dinner", "Clean Up")
val myTasks = setOf("Eat Breakfast", "Clean Up", "Work", "Eat Lunch", "Clean Up", "Work", "Eat
Dinner", "Clean Up")
println(task)
println("$taskIndex: $task")
}
Output:
My Home
Course Menu
Workspace restored.
Get Unstuck
Tools
Learn
LOOPS
Iterating Through Maps
Unlike a list or a set, a map is a collection of entries. When using a map as a for loop iterator, we
can iterate through each entry of the map or through just the keys, or just the values.
When iterating through a map, the loop variable will hold one entry per iteration. The entry’s key
and value can be accessed using the properties, key and value:
We can also access the key and value of each entry by destructuring using two loop variables in
parentheses. The first variable is the entry’s key and the second is the value:
println("KEYS")
for (itemName in myClothes.keys) {
println(itemName)
}
println("\nVALUES")
for (itemCount in myClothes.values) {
println(itemCount)
}
Here is the output:
KEYS
Shirts
Pairs of Pants
Jackets
VALUES
7
4
2
Instructions
1.
The map favoriteColors holds the names of people and their favorite colors. The keys of the
map are the people’s names and the values of the map are their favorite colors. Start by iterating
through the map favoriteColors to access each entry and output its key and value.
Be sure to use curly brackets in the string template when accessing the attributes of the entry in
the loop variable.
Checkpoint 2 Passed
Hint
Create a for loop with favoriteEntry as the loop variable and favoriteColors as the iterator. The
loop body should use println() to output the string template "${favoriteEntry.key}: $
{favoriteEntry.value}".
Hint
Create a second for loop with color as the loop variable and favoriteColors.values as the
iterator. The loop body should use println() to output the loop variable.
println("${favoriteEntry.key}: ${favoriteEntry.value}")
println(color)
}
LOOPS
while Loop
When repeating code we may not have a range or defined collection to dictate the number of
loops we need to execute. In this case, we can rely on a while loop which repeats code as long as
a specified condition is true. If we revisit the animation in the first exercise, we can see that
Codey uses a while loop to hike until time is no longer less than 17.
A while loop is similar to an if expression because it tests a condition and when the condition
is true a body of code is executed. The main difference is the while loop will complete the body
of code, check the condition, and repeat the code if the condition is still true. If the condition
is false, the while loop is done and the program moves on:
I am a teenager. // myAge is 16
I am a teenager. // myAge is 17
I am a teenager. // myAge is 18
I am a teenager. // myAge is 19
I am not a teenager. // myAge is 20
If myAge wasn’t incremented inside the loop body the loop condition would always be true and
repeat forever. This is known as an infinite loop. Infinite loops lead to application crashes or
other unwanted behavior so it is important that they are avoided.
When a while loop condition never evaluates to true, the entire block of code is skipped:
1.
Create a while loop that:
Hint
Create a while loop with the condition counter < 5. The loop body should contain println() to
output the value of counter as well as increment counter using the ++ operator.
while (conditionIsTrue) {
println(counterVariable)
counterVariable++
}
2.
A while loop condition can also check the elements of a collection. You’ll use another counter
variable, index, to access the collection’s elements.
When you’re done, you’ll see that the while loop exits once the element “6th” is the current one.
Hint
Create a while loop with the condition myFeelings[index] != "happy". The loop body should
use println() to output the value of myFeelings[index] as well as increment index using the +
+ operator.
fun main() {
var counter = 0
var index = 0
val schoolGrades = listOf("Kindergarten", "1st", "2nd", "3rd", "4th", "5th", "6th", "7th")
While.kt
fun main() {
var counter = 0
var index = 0
val schoolGrades = listOf("Kindergarten", "1st", "2nd", "3rd", "4th", "5th", "6th", "7th")
println(counter)
counter +=1
println(schoolGrades[index])
index++
Output:
LOOPS
do..while Loop
A do..while loop is just like a while loop except the looping condition is checked at the end of the
loop body. This is known as an exit-condition loop and means the code in the body will execute
at least once:
do {
print("I loop once!")
} while(myCondition)
This example shows that even though we have a false condition our loop will still run the loop
body once:
I loop once!!!!
One reason we would use a do..while loop is when our loop condition initialization and update
commands are the same. Using psuedocode we can compare a while loop with a do..while loop
using how someone might decide to go outside:
Is it sunny outside?
while ( not sunny ) {
Is it sunny outside?
Stay inside.
}
Go outside!
The while loop example has a line before the loop to check if it is sunny outside. The loop is
entered if it is not sunny and then repeatedly checks if it is sunny outside. When it is sunny, the
loop exits and it’s time to go outside:
do {
Is it sunny outside?
Stay inside.
} while ( not sunny )
Go outside!
The do..while loop enters the loop and starts by checking if isSunny is true. The loop body
repeats if the isSunny is false.
The extra check prior to the loop is unnecessary since it is performed inside the loop anyway. If
we have to look outside to get our initial loop condition and to update our loop condition, we
might as well have that be the loop body and check the condition at the end.
This difference may seem subtle, but if this loop is executed hundreds or thousands of times a
second, removing the one line of code using a do..while loop may save time.
Instructions
1.
We’ll implement a do..while loop that performs a Celsius to Fahrenheit temperature conversion.
First, construct a do..while loop that checks if fahr does not equal 212.0. Inside the loop body:
Hint
Implement a do..while loop with the loop condition, celsiusTemps[counter] != 212.0. Inside the
loop body, copy the 2 lines of code in the instructions and increment the index variable using
the ++ operator.
do {
fahr = celsiusTemps[counter] * fahr_ratio + 32
println(fahr)
listIndex++
} while (conditionIsTrue)
fahr = celsiusTemps[counter] * fahr_ratio + 32 is the conversion equation from Celsius to
Fahrenheit: FahrenheitTemp = (CelsiusTemp * 9/5) + 32.
fun main() {
var index = 0
do {
println("${celsiusTemps[index]}C = ${fahr}F")
index ++
} while (fahr != 212.0)
}
My Home
Course Menu
Workspace restored.
Get Unstuck
Tools
Learn
LOOPS
Nested Loops
Loops inside loops, oh my! A nested loop represents one loop placed inside the body of another
loop which results in a higher dimensions of iterations. This strategy is most often used when
we’d like to compare the contents of two different collections/iterators.
Below is an example of nested loops. The outer loop iterates through the range 1..2 and the inner
loop iterates through the range 'A'..'C':
for (i in 1..2) {
for (j in 'A'..'C') {
println("Outer loop: $i - Inner loop: $j")
}
}
It’s important to understand that for every iteration in the outer loop, the inner loop will run
through all of its own iterations.
In the example above, the inner loop iterates 3 times for each of the outer loop’s 2 iterations.
Therefore, the println() statement is run 6 times:
Instructions
1.
You’ll be building a grid of rows and columns much like the ones that exist in Google and Excel
sheets using nested loops. First start with a single loop.
Hint
Create a for loop with i as the loop variable and 1..6 as the iterator. The loop body should be
empty.
The empty space at the end of the String template is used to create a gap between columns which
helps us visualize what is happening in the code.
Checkpoint 3 Passed
Hint
Create a for loop inside the first loop, with j as the loop variable and 'A'..'F' as the iterator.
The loop body should have a print() statement that outputs this string template "$j$i ".
Outside of the inner loop but still inside of the outer loop:
add an empty println() statement.
When you run the code you can now see that each inner loop iteration outputs a column, while
each outer loop iteration creates a new row.
Checkpoint 4 Passed
Hint
Add a blank println() statement to the end of the outer loop. The println() will create a new
row in the output.
for(outerLoopVar in outerIterator) {
for(innerLoopVar in innerIterator) {
print("$innerLoopVar$outerLoopVar")
}
println()
}
fun main() {
for (i in 1..6) {
for (j in 'A'..'F') {
print("$j$i ")
println()
}
My Home
Course Menu
Connected to Codecademy
Get Unstuck
Tools
Learn
LOOPS
Jump Expressions
The jump expressions, break and continue, are used to change the standard loop behavior by
exiting a loop early or skipping a single repetition.
We can see the below output stops before printing the number 12:
Output
4
8
2
9
The continue expression will skip the current execution of the loop body, but the loop will keep
going if there are iterations left. If the continue expression gets executed, any code left in the
current iteration will be skipped:
Output
4
8
2
9
7
3
The first example outputs the elements in myNumbers until you reach one greater than 9. The
second example outputs all elements in myNumbers except those that are greater than 9.
Since jump expression are usually contained inside if expressions, they gives us the ability to
add a condition to exit a for loop or using another condition to exit a while loop.
Don’t worry if this all doesn’t stick right away; keep practicing with each jump expression and
you’ll quickly get the hang of how and when each one is used.
Instructions
1.
The code on the right is “looking” for something in different rooms of a house. Thankfully we
know that the item being searched for is in the "Living Room".
Your job is to instruct the for loop to stop looking once it reaches "Living Room":
Hint
In the first for loop, add an if expression with the condition room == "Living Room". Inside
the if expression, output “Found It!” using println(). Inside the if statement add
a break expression.
for(room in rooms) {
print("Searching $room: ")
// Write your code below
if (condition) {
println(message)
break
}
println("Found Nothing")
}
2.
Good work! We also come across situations where we may want to skip a loop iteration. The
second for loop in the editor causes a division by zero error. This is undesirable, and we need to
add code to the body of the for loop to avoid this.
Hint
In the second for loop, add an if expression with the condition number == 0. Inside
the if expression add a continue expression. When you run the code you should see no more
error and the output from each iteration EXCEPT when number is 0.
fun main() {
print("$room: ")
println("Found Nothing.")
println("120/number = ${120/number}")
fun main() {
print("$room: ")
println("Found It!")
break
}
println("Found Nothing.")
if (number == 0) {
continue
println("120/number = ${120/number}")
}
Learn
LOOPS
Labeled Jump Expressions
“How would we use jump expressions inside nested loops?” Good question! The answer
is labeled jump expressions. By adding a label to the outer loop of nested loops, we can execute a
jump expression from the inner loop and have it act on the labeled outer loop.
First we need to give a name to our label. In the following example we choose the name rps. The
outer loop is marked using our label rps followed by the @ symbol:
Instructions
1.
Recall the 6x6 grid with “A1” to “F6”” cells from the previous exercise. We’ll take a closer look
at how we can manipulate the structure and output of this grid using labeled jump expressions.
Hint
Add the label grid to the outer loop.
Hint
Add an if expression with the condition j == 'C' at the top of the inner loop.
Once you run the code you should see a single line of output. The outer loop numbers go
from 1 through 6, but the inner loop letters only go up through 'B'.
It is important to note that the println() statement at the end of the outer loop is also skipped.
The result is only one row is printed. This shows that a labeled continue will skip any code
proceeding it in the inner loop and at the end of the outer loop.
Checkpoint 4 Passed
Hint
Add a labeled continue expression with the label grid.
fun main() {
for (j in 'A'..'F') {
if (j == 'C') {
continue@grid
print("$j$i ")
println()
}
https://github.com/Codecademy
https://github.com/Codecademy
https://github.com/Codecademy
https://github.com/Codecademy
https://github.com/Codecademy
https://github.com/iaahmed220/codecademy-projectshttps://github.com/iaahmed220/codecademy-
projects
https://github.com/iaahmed220/codecademy-projects
https://github.com/iaahmed220/codecademy-projects
https://github.com/Codecademy/learn-kotlin/blob/main/5-loops/Shapes.kt
fun
main(
) {
// Square Variables
val sqSide = 7
val sqChar1 = "X "
val sqChar2 = "O "
// Write your code below
for (i in 1..sqSide) {
for (j in 1..sqSide) {
if (i % 2 == 0 && j % 2 == 0 || i % 2 == 1 && j % 2 ==1) {
print(sqChar1)
} else {
print(sqChar2)
}
}
println()
}
// Triangle Variables
val triRows = 10
var triCount = 0
var triRowLen = triRows
val triChar1 = "/ "
val triChar2 = " "
triRowLen = triRows
for (i in triRows downTo 1) {
while (triCount < triRowLen) {
triCount++
if (triCount != 1 && triCount != triRowLen && i != triRows)
{
print(triChar2)
} else {
print(triChar1)
}
}
println()
triCount = 0
triRowLen--
}
}
Brief
Objective
LEARN KOTLIN
Shape Maker
How many output statements do you need to draw two-dimensional shapes? Using loops, the
answer to this question is 2. In this project, you will create a square and a triangle of any size
using nested loops with one print() statement and one println() statement.
We’ll create a basic square pattern using loop concepts we covered in the previous lesson. We’ll
even take it a step further by getting our program to output a checkerboard pattern.
Then, we’ll explore how nesting a while loop inside of a for loop can be used to create a triangle
pattern in the output terminal. This will give us a different perspective of nested loops and how
to control variables when using while loops.
Tasks
14/14 Complete
Mark the tasks as complete by checking them off
Creating a Square Pattern
1.
In Shapes.kt, there are two groups of variables: one for making a square and one for making a
triangle.
The first group of variables will be used to draw a square using nested for loops:
sqChar1 and sqChar2 each represent one column and are each 3 characters long to account for the
space between rows.
Review the variables and move to the next task when ready.
Hint
Square Variable Group:
val sqSide = 7 defines the side length and will create a square of 7 x 7 characters.
val sqChar1 = "X " defines the output character String used to create the square.
val sqChar2 = "O " defines the output character String used to help create the checker
board.
2.
Start your code under the first group of variables by creating a for loop with an iterator that starts
at 1 and goes through the value of sqSide. This will act as the outer loop of the code.
Put a blank println() in the loop body. This will create the rows of the square.
Stuck? Get a hint
3.
Now, let’s add an inner loop to output each column in a row.
Inside the outer for loop, create an inner for loop before the println() statement. Use the same
iterator as the outer loop.
Inside the inner loop body use a print() statement to output the value of sqChar1.
Hint
Follow this syntax to define the inner loop and character output:
X X X X X X X
X X X X X X X
X X X X X X X
X X X X X X X
X X X X X X X
X X X X X X X
X X X X X X X
Creating a Checker Board Pattern
4.
To create a checker board, we need to use the loop variables in an if expression to decide which
character to output.
Otherwise, output sqChar2.
Hint
Use the modulus (%) operator to test if the loop variables are both even OR both odd.
Even Condition:
if ( EVEN condition) {
print(stringVar1)
} else if (ODD Condition) {
print(stringVar1)
} else {
print(stringVar2)
}
The output should resemble:
X O X O X O X
O X O X O X O
X O X O X O X
O X O X O X O
X O X O X O X
O X O X O X O
X O X O X O X
Creating a Triangle Pattern
5.
Now we’ll move on to creating a triangle pattern.
Take a look at the next group of variables that will be used to draw a triangle:
Review the variables and move to the next task when ready.
Hint
Triangle Variable Group:
6.
Start off the code for the triangle pattern by using a for loop that counts down from triRows to 1.
This will act as the outer loop of the code.
Increment triCount inside the loop. Make sure to run your code only after you’ve added the
increment, otherwise, you’ll run into an infinite loop. If you have, you might need to refresh the
web page.
Hint
Follow this syntax to define the inner loop and triCount incrementation:
for (outerLoopVar in numRows downTo 1) {
while (countVar < rowVar) {
countVar++
}
println()
}
8.
Add a print() statement to the while loop body directly below the increment to output triChar1.
Run the code and look at the output. Do you see a single line of characters? Can you figure out
why your output is the way it is?
Hint
Follow this syntax to include the print() statement inside the inner loop:
To prevent this, outside the while loop (but inside the for loop), set triCount to its initial value, 0.
This will ensure that at the start of each iteration of the for loop, triCount is less
than triRowLen and the while loop body will execute.
Hint
Follow this syntax to reset the value of triCount to 0:
To make our pattern look like a triangle, we need to adjust the length of each new row. To
accomplish this, decrement the value of triRowLen at the end of the for loop’s body.
Hint
Follow this syntax to decrement the value of triRowLen:
/ / / / / / / / / /
/ / / / / / / / /
/ / / / / / / /
/ / / / / / /
/ / / / / /
/ / / / /
/ / / /
/ / /
/ /
/
Creating a Triangle Outline Pattern
11.
We’re going to modify our triangle code to just output the triangle’s outline. Feel free to make a
copy of the code created in steps 6-10 if you want to keep the full triangle output.
If you copied the code to make a 2nd triangle, be sure to set the value
of triRowLen to triRows just prior to the newly copied code.
Confirm the output of a 2nd triangle and move to the next task to implement the triangle outline.
Hint
Reset the value of triRowLen with the following statement, triRowLen = triRows and copy your
previous code over to start the triangle outline:
rowVar = numRows
/ / / / / / / / / /
/ /
/ /
/ /
/ /
/ /
/ /
/ /
/ /
/
Optional
13.
Great work on the project! Here are a couple more tasks you can work on if you want to keep
going.
Change the values of sqChar1, sqChar2, triChar1 and triChar2 to see how they affects the
look of each shape.
Use different conditions within the if expressions of the square shape to explore what
other patterns you can generate.
In the triangle outline code, instead of using an else to output triChar1, use a continue in
the if block to skip the rest of the while loop code.
Hint
Optional task 1:
In the square code, you can change the condition of the if expression to:
Optional task 3:
In the triangle outline code, remove the else statement and put continue at the end of
the if block:
if (countVar > 0 && countVar < rowVar && outerLoopVar != numRows ) {
print(stringVar2)
continue
}
print(stringVar1)
This accomplishes the triangle outline by printing triChar2 and skipping the output
of triChar1 when the condition is true. Otherwise the code will output triChar1.
14.
Sample Solutions:
Shapes.kt
A function header contains valuable information about a function including its name, arguments,
and its return type.
We’ll cover arguments and return types later in this lesson. For now, we’ll focus our attention on
creating a basic function that outputs a value whenever we call it.
fun greeting() {
println("Hello friend!")
}
A function will only execute when it is called or invoked. While the function greeting() will
exist outside the main() function, we will call greeting() within main() by writing the function’s
name followed by parentheses:
fun greeting() {
println("Hello friend!")
}
fun main() {
// Invoke the function
greeting()
}
// Prints: Hello friend!
Anytime we call greeting(), "Hello, friend!" will be outputted to the terminal.
Instructions
1.
Create a function named smores() that outputs the following statements using println():
"Roast a marshmallow."
"Place marshmallow on a graham cracker."
"Place chocolate on marshmallow."
"Put a new graham cracker on chocolate."
"Enjoy!"
Hint
To create a function, create a function header and body. The function header will contain
the fun keyword, the function name, a pair of empty parentheses (( and )) and curly brackets
({ and }) to hold the function body:
fun functionName() {
println("Statement 1")
println("Statement 2")
println("Statement 3")
println("Statement 4")
println("Statement 5")
}
2.
Invoke smores() in the main() function.
Hint
Inside the main() function, write the name of the function followed by parentheses (( and )) to
invoke the function:
fun main() {
functionName()
}
3.
Optional:
Call smores() again. Note how time is saved by calling a function instead of writing the
instructions again.
Hint
Using the smores() function, we can output the 5 println() statements using a single function
call.
fun smores() {
println("Roast a marshmallow.")
println("Enjoy!")
fun main() {
smores()
}
FUNCTIONS
Arguments
Arguments are pieces of data we can feed to our functions in order to produce dynamic results.
We can include as many arguments as the function needs.
Think of the println() function. When we use it, we give it a single argument: a String value.
This value is then passed and outputted to the terminal.
To pass arguments into a function, we need to add parameters to our function header. Parameters
are the names given to data being passed into a function. For example:
The parameters can then be referenced within the function body like a variable. The value of
each parameter is determined by the arguments used when invoking the function:
calculateForce(5, 12)
When calculateForce() is called, the values 5 and 12 are passed as arguments into the function.
The value of the parameter mass will be 5 and the value of acceleration will be 12. Invoking the
function with these argument values will give us the following output:
Instructions
1.
Create a function called getSpeed() that accepts two Int arguments: distance and time.
Inside the function, create a variable called speed that is equal to the value of distance / time.
If we have a function that accepts an Int argument called num and a String argument named text,
our header would look like this:
fun main() {
functionName(argument1, argument2)
}
fun main() {
getSpeed(10, 3)
}
My Home
Course Menu
Connected to Codecademy
Get Unstuck
Tools
Learn
FUNCTIONS
Named and Default Arguments
We can go further with arguments by naming them or setting default parameter values.
To improve the readability of our code, we can name our arguments when invoking the function.
For example, with our calculateForce() function, we can add the names of arguments to our
function call:
fun main() {
// Invoke the function with named arguments.
calculateForce(acceleration = 12, mass = 5)
// Prints: The force is 60 Newtons.
}
Note that by naming our arguments when we invoke a function, we do not need to place the
arguments in the same order as they appear in the function header.
Default arguments provide values to function arguments if none are given when the function is
called. To implement this, we add an assignment operator and a value after the argument in the
function header, like so:
Instructions
1.
An online shop has a special coupon code to get 15% off a customer’s final purchase.
Outside the conditional, use println() and a String template to output the following statement:
Invoke getPrice() for a second time. This time, only give the program a single argument: 48.0.
if (couponCode == "save15") {
} else {
finalPrice = price
}
fun main() {
}
My Home
Course Menu
Connected to Codecademy
Get Unstuck
Tools
Learn
FUNCTIONS
Return Statements
The functions in the previous exercises produced output via println() statements contained
within its code body; however, we also have the ability to return a value from a function.
A return statement returns a value from a function and passes it back to where the function was
invoked. This value can then be used throughout our program.
If we want a function to return a value, we must add the return type to the function header as
well as a return statement in the body. Take a look at the following example where we create a
function that takes in a list of Ints and returns an Int value:
The return type describes the data type of the value being returned and is stated after the
parentheses and a colon : in the function header.
The keyword return is used to declare a return statement. In this case, sum is the value
being returned.
Any lines of code that exist after the return statement will not be executed.
Previously, we invoked functions by calling them on their own line of code; however, we can
also invoke a function and assign it to a variable for later use.
For example, we can set total to the return value of listSum() after sending it a list of Int values
(billsToPay):
Instructions
1.
Following a recipe for vanilla cake, you are asked to add .75 ounces of vanilla extract; however,
you only have a teaspoon to measure the ingredients.
Inside the function, create a variable tsp whose value is oz multiplied by 6. Use a return
statement to return the value of tsp.
Hint
To return a value from a function, add a return type to the function header.
If we had a function that took in an Int as an argument and a Boolean as a return value, our
header would look like this:
return valueToReturn
2.
Inside main(), create a variable called tspNeeded and set its value to ozToTsp() with an argument
of .75.
You will need [tspNeeded] tsp of vanilla extract for this recipe.
Hint
To invoke the function, set it as the value of a variable:
var tsp = oz * 6
return tsp
fun main() {
println("You will need $tspNeeded tsp of vanilla extract for this recipe.")
}
My Home
Course Menu
Connected to Codecademy
Get Unstuck
Tools
Learn
FUNCTIONS
Single Expression Functions
If one of our functions contains only a single expression, we can write the function out with
shorthand syntax. This syntax allows us to create a function using only a single line of code.
For example, assume we create a function that returns a given number (num) to the power of 2.
Using the normal function syntax, our code would look like this:
We can shorten this code even more by removing the return type. Using type inference, the
compiler can deduce the type of the return value, making our function look like this:
Instructions
1.
Create a single expression function called pyramidVolume().
The function will accept three Int types arguments: l, w, and h and return the value of (l * w *
h) / 3.
Hint
If we needed a single expression function that returned the product of two numbers, our code
would look similar to the example below:
fun main() {
var length = 5
var width = 8
var height = 14
My Home
Course Menu
Workspace restored.
Get Unstuck
Tools
Learn
FUNCTIONS
Single Expression Functions
If one of our functions contains only a single expression, we can write the function out with
shorthand syntax. This syntax allows us to create a function using only a single line of code.
For example, assume we create a function that returns a given number (num) to the power of 2.
Using the normal function syntax, our code would look like this:
We can shorten this code even more by removing the return type. Using type inference, the
compiler can deduce the type of the return value, making our function look like this:
Instructions
1.
Create a single expression function called pyramidVolume().
The function will accept three Int types arguments: l, w, and h and return the value of (l * w *
h) / 3.
Checkpoint 2 Passed
Hint
If we needed a single expression function that returned the product of two numbers, our code
would look similar to the example below:
fun product(num1: Int, num2: Int) = num1 * num2
2.
Inside main(), create a variable called volume and set its value to pyramidVolume() with the
following arguments in their respective order: length, width, height.
Hint
To invoke the function, set it as the value of a variable:
fun main() {
var length = 5
var width = 8
var height = 14
}
FUNCTIONS
Function Literals
To simplify how we define functions, we can use function literals. A function
literal is an unnamed function that can be treated as a value: we can call them,
assign them as variables, pass them as arguments, and return them from a
function as we could with any other value.
We’ll be going over two types of function literals: anonymous functions and
lambda expressions. While anonymous functions and lambda expressions
serve the same purpose, they use a slightly different syntax.
The function type describes the argument type and return type of the
anonymous function. The arguments are contained within parentheses while
the return type is stated after ->. In this case, the anonymous function takes in
two Doubles and returns a single Double.
val quotient = { num1: Int, num2: Int -> num1 / num2 }
To learn more about anonymous functions and lambda expressions, check out
the Kotlin Language Guide.
Instructions
1.
Working at a landscape company, a customer asks for grass to cover the area
of their triangle-shaped yard.
var variableName = { arg1: Int, arg2: Int, arg3: Int -> (arg1
+ arg2) * 2 }
landscape.kt
fun main() {
// anonymous function
println(area(15, 19))
// lambda expression
println(perimeter(15, 24))
}
FUNCTIONS
Review
Congratulations on completing this lesson. Let’s go over what we learned:
https://www.codecademy.com/courses/learn-kotlin/lessons/kotlin-using-text-variables/exercises/user-
input
https://www.codecademy.com/courses/learn-kotlin/articles/kotlin-recursion
https://en.wikipedia.org/wiki/Stack_overflow
https://www.codecademy.com/courses/learn-kotlin/lessons/kotlin-classes/exercises/introduction-to-
classes
claas of kotlin
My Home
Course Menu
Connected to Codecademy
Get Unstuck
Tools
Learn
CLASSES
Creating a Class
Now let’s practice writing our own classes. A Kotlin class is declared at the top of a Kotlin file,
outside the main() function, with the class keyword followed by its name:
class Name {
// class body
}
The name of a class should always start with an upper case letter and use the camel case form.
The class body is contained within curly braces and will hold all of the properties and functions
related to that class. We will take a closer look at class functions in a later exercise.
Note: It is optional for a Kotlin class to contain a body, thus if the class has no body, we can
omit its curly braces, resulting in the following declaration:
class Name
Let’s revisit our real-world, Car example. Suppose we create the following class:
class Car
Our blueprint is complete! But it’s not of much use to us empty. Any car possesses several
properties including the year it was made, its model name, and color. Let’s add these:
class Car {
val year = 2011
val model = "Jeep"
val color = "Blue"
}
We’ve created the properties, year, model, and color and initialized them with values. Now any
time we create a car object from this class, it will possess the
properties, year, model and color and hold their respective values. In the next exercise, we’ll
learn how to create objects from a class. For now, let’s practice with the Kotlin class syntax. 🚗
Instructions
1.
In Book.kt, declare an empty class called Book.
Checkpoint 2 Passed
Hint
An empty class can be created with the following syntax:
class Name {
}
2.
Add the following properties and the values they hold:
Hint
A book has a total number of pages, possesses an author and a title. We can use these properties
within our class as so:
class Name {
var property1 = 320
var property2 = "Harry Potter and the Sorcerer's Stone"
var property3 = "J.K. Rowling"
}
class Book {
fun main() {
}
My Home
Course Menu
Workspace restored.
Get Unstuck
Tools
Learn
CLASSES
Creating an Instance
Now that we’ve created our first class, let’s create an instance of it. An instance of a class
resembles an object that is a member of that given class.
class Car {
val year = 2011
val model = "Jeep"
val color = "Blue"
}
To make an instance of this class, we’d utilize the following syntax:
We’ve declared the name of our instance/object to be myCar. This name is arbitrary and is
up to the developer’s choosing.
Following the assignment operator, we’ve invoked the Car class with the name of the
class followed by parentheses - the same syntax we use when invoking a function.
With this line of code, the myCar instance now possesses all the properties and their
respective values that were specified within the class body.
Just like we’ve done with Kotlin’s built-in properties such as .length and .size, we can utilize
the dot notation and append our class property names on our instance/object and retrieve their
values.
Instructions
1.
Within the main() function of Building.kt, create an instance of the Building class and assign it
to the variable, residentialBuilding.
Checkpoint 2 Passed
Hint
Implement the following syntax in your code:
Hint
Use the following syntax for each property call:
Hint
With each and every instance created for the Building class, the values will always be 2016, 400,
and "Limestone". This may work for some programs but not for most where we’d most likely
need to have custom values set for each instance. There’s a very small chance that one residential
building has the same exact characteristics as another commercial building!
class Building {
}
fun main() {
println(residentialBuilding.yearBuilt)
println(residentialBuilding.height)
println(residentialBuilding.type)
}
class Building {
fun main() {
println(residentialBuilding.yearBuilt)
println(residentialBuilding.height)
println(residentialBuilding.type)
}
CLASSES
Primary Constructor
Looking to customize your instances? You’ve come to the right place! Kotlin
classes provide us with something called a primary constructor that allows us
to declare properties and initialize them when we instantiate an object.
class Name {
val x = "some value"
val y = "another value"
}
Each property would already have its default value set, but with primary
constructors, we give our program the ability to set the values when an
instance is created.
class Car(val year: Int, val model: String, val color: String)
Neat, right? Let’s see it in action.
Instructions
1.
In Person.kt, add a class, Person that contains a primary constructor with the
following properties:
name with the type, String
age with the type, Int
favoriteColor with the type, String
Hint
Keep the following syntax in mind when creating your class:
class Person(val name: String, val age: Int, val favoriteColor: String)
fun main() {
}
My Home
Course Menu
Connected to Codecademy
Get Unstuck
Tools
Learn
CLASSES
Member Functions
Now let’s explore how to add even more functionality to our classes with functions. A function
declared within a Kotlin class is known as a member function.
Member functions possess the same qualities and abilities as the user-designed functions you’ve
learned about in the previous lesson. The syntax is the same as well. Some things to keep in
mind:
When an instance of a class is created, the object has access to any and all functions that
exist within the class body.
Unlike the code within the init block which executes automatically, the code within the
functions will only execute when the function is called.
For example,
fun speak() {
println("Meow!")
}
}
We’ve created a simple class, Cat, with a primary constructor and a single member function. We
can now create an instance of the class as so and call the speak() function:
Instructions
1.
Inspect the class, Dog, on the right. Inside the init block, we looped through the list
property, competitionsParticipated. Now, let’s add a member function below the init block that
shows off one of the dog tricks done in the competition.
fun speak() {
println("$dog says: Woof!")
}
2.
Create an instance of the Dog class within the main() function. Call the instance, maxie. Pass in the
following custom values for the properties:
name: "Maxie"
breed: "Poodle"
list of competitions should include "Westminster Kennel Club Dog
Show" and "AKC National Championship"
Run your code. Then, call the speak() function on maxie on the following line.
Hint
Within the main() function, add the following instance:
dogName.speak()
My Home
Course Menu
Workspace restored.
Get Unstuck
Tools
Learn
CLASSES
Member Functions
Now let’s explore how to add even more functionality to our classes with functions. A function
declared within a Kotlin class is known as a member function.
Member functions possess the same qualities and abilities as the user-designed functions you’ve
learned about in the previous lesson. The syntax is the same as well. Some things to keep in
mind:
When an instance of a class is created, the object has access to any and all functions that
exist within the class body.
Unlike the code within the init block which executes automatically, the code within the
functions will only execute when the function is called.
For example,
fun speak() {
println("Meow!")
}
}
We’ve created a simple class, Cat, with a primary constructor and a single member function. We
can now create an instance of the class as so and call the speak() function:
Instructions
1.
Inspect the class, Dog, on the right. Inside the init block, we looped through the list
property, competitionsParticipated. Now, let’s add a member function below the init block that
shows off one of the dog tricks done in the competition.
Hint
Make sure to use the following syntax in your function code:
fun speak() {
println("$dog says: Woof!")
}
2.
Create an instance of the Dog class within the main() function. Call the instance, maxie. Pass in the
following custom values for the properties:
name: "Maxie"
breed: "Poodle"
list of competitions should include "Westminster Kennel Club Dog
Show" and "AKC National Championship"
Run your code. Then, call the speak() function on maxie on the following line.
Checkpoint 3 Passed
Hint
Within the main() function, add the following instance:
dogName.speak()
dog.kt
class Dog(val name: String, val breed: String, val competitionsParticipated: List<String>) {
init {
}
}
fun speak() {
fun main() {
var maxie = Dog("Maxie", "Poodle", listOf("Westminster Kennel Club Dog Show", "AKC National
Championship"))
maxie.speak()
}
CLASSES
Review
Excellent work! In this lesson, we’ve learned the following concepts:
Instructions
You did it! 🎉 You’ve completed the last lesson in the Learn Kotlin course. You should be
immensely proud of yourself and your accomplishments. This was no easy feat, but you’ve made
it to DevCity and can proudly say you’re on track to becoming a master of the Kotlin language.
Run the code on the right and enter the following two commands for a special message from
Codey:
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a look at this
material's cheatsheet!
Community Forums
Run
Terminal
7/7
Back
class Congratulations(val name: String) {
init {
println("Dear $name,")
fun message() {
println("Thank you for embarking on this journey with me. I couldn't have gotten through the
treacherous waters of Conditional Creek or hiked up the Looping mountains without your help. You now
have the fundamental knowledge to go on and continue your Kotlin journey in the world of android
application, web development or more. The world is yours. Good luck! ")
fun signOut() {
fun main() {
toLearner.message()
toLearner.signOut()
}
class
Calculator(va
l name:
String) {
init {
println("$name's Calculator 🧮")
}
fun main() {
var myCalculator = Calculator("Codey")
println(myCalculator.add(5, 7))
println(myCalculator.subtract(45, 11))
println(myCalculator.divide(8, 0))
println(myCalculator.power(2, 1))
}
Contact GitHub
Pricing
API
Training
Blog
About
My Home
Course Menu
Connected to Codecademy
Get Unstuck
Tools
Brief
Objective
LEARN KOTLIN
Codey's Calculator
Codey’s made it to DevCity: a place full of Android applications, web development, and other
endless implementations of the Kotlin language!
In this project, we’ll utilize our knowledge of Kotlin classes to help Codey build a basic
calculator application that many of us have built-into our smartphones.
A variation of this project exists in our Learn Java course so if you’re learning Kotlin with a Java
background, we highly recommend comparing the syntaxes and code implementations once
you’ve completed this project to better understand the similarities and differences between the
two languages.
Tasks
12/13 Complete
Mark the tasks as complete by checking them off
Create a Class
1.
The first step in creating Codey’s individual calculator is to generate a blueprint.
In Calculator.kt, declare the class, Calculator, that accepts a name property within its primary
constructor.
class Name
To add a primary constructor with a single property, make sure to implement the following code
and specify the property type:
init {
println("$name's Calculator 🧮")
}
String concatenation can also be used in your statement instead.
Add the Calculator's Functions
3.
Now, let’s give our calculator the ability to make calculations.
First, declare a member function called, add(), which should calculate and return the sum of two
Integer values.
Hint
Mimic the following function header in your code:
Implement the multiply() function which will calculate and return the product between two
Integer values.
Hint
Mimic the following function header in your code:
The member function should return an error message if the user tries to divide by 0.
Hint
Mimic the following function header in your code:
if (param2 == 0) {
return "Error! Dividing by zero is not allowed."
} else {
return param1 / param2
}
Notice how because the conditional can return either a String or Int type, it was important for us
to specify Any in the function header.
7.
Lastly, create the power() function which should calculate and return the first parameter raised to
the power of the second.
Think of how you can implement this within the function body. Give it a shot in the code editor.
Move on to the next step for guided instruction.
Hint
Use the following syntax to create the power() function:
To achieve the power calculation, use a looping technique to iterate over each value, from 1 to
param1. Within the body of the loop, reassign the value of result to be result times param2.
If your first parameter is x and your second parameter is y, we can set up the following code:
for (i in 1..y) {
resultVar *= x
}
return resultVar
Get to Calculating
9.
Now that we’ve implemented several arithmetic functionalities, let’s spring our calculator to
action. If you haven’t already done so, below the class, declare a main() function.
In it, create a variable name of your choosing that will store an instance of the Calculator class.
Pass in the name, "Codey" in the class call, and run your code. You should see the output
statement from the init block.
Hint
Utilize the following syntax in your object creation:
println(myCalculator.subtract(45, 11))
// Prints: 34
println(myCalculator.divide(8, 0))
// Prints: Error! ...
println(myCalculator.power(2, 1))
// Prints: 2
Optional Challenges
12.
Excellent work! If you’re up for a challenge, check out these additional tasks:
To mimic a real-world calculator, we can format our output to also include the original
calculation. 12 -> 5 + 7 = 12.
Having the code as is without any additional output, we can refactor some of the member
functions to utilize a single expression syntax and shorten the lines of code that they span.
We can add another member function to the class that you’d like your calculator to
perform.
Hint
For the first task, we can utilize print() statements and String templates to add a line of code
similar to this one to the top of each function:
To do so, we’d need to accept the percent number in Int form and then convert it to decimal
within the function:
Calculator.kt
init {
return a + b
return a - b
return a * b
if (b == 0) {
return "Error! Dividing by zero is not allowed."
} else {
return a / b
var result = 1
for (i in 1..b) {
result *= a
return result
fun main() {
println(myCalculator.add(5, 7))
println(myCalculator.subtract(45, 11))
println(myCalculator.divide(8, 0))
println(myCalculator.power(2, 1))
}
Sample
https://github.com/Codecademy/learn-kotlin/blob/main/7-classes/Calculator.kt