In addition to adding and removing elements from a set, the set collection supports a myriad of other functionalities. You can find the entire list in Kotlin’s documentation.

In this exercise, we’ll explore some of the most common set functions using the following example:

var numbers = setOf(10, 15, 20, 25)

To retrieve, the first element of any set, we can use the first() function:

numbers.first() // 10

To retrieve the last element of any set, we can use the last() function:

numbers.last() // 25

Finally, if we’d like to sum up all of the elements in a set, we can use the sum() function:

numbers.sum() // 70

Note: To see the output of each function call on a set, it must be wrapped in a print statement.



In Midterm.kt, we’ll write a program that determines if a class has failed or passed a midterm.

First let’s gather the grades, and store them in a mutable set, testGrades, with the following numerical values:

  • 65
  • 50
  • 72
  • 80
  • 53
  • 84

Next, we’ll utilize the following formula to declare 3 variables that we’ll use to calculate the average:

average = sum /number of elementsaverage \ = \ sum \ / number \ of \ elements
  • First, declare the variable, sum, and within it store the result of calling the sum() function on testGrades.
  • Declare the variable, numStudents, and within it store the result of using the size property on testGrades.
  • Finally, declare the variable, average and assign it the division expression of sum divided by numStudents.

Lastly, set up a conditional that follows this logic:

  • If the average grade is less than 65, then output the text, "Failed".
  • Otherwise, output the text, "Passed".

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?