Managing Course Enrollments with Kotlin Sets
Introduction
Welcome to today's lesson! We'll explore a practical application of Kotlin's set capabilities by managing student enrollments for various courses. Imagine you're running an online course platform and need to handle enrollments, checks, and listings of students in different courses. Sets are perfect for this kind of problem as they don’t allow duplicates, ensuring that a student can't enroll in the same course more than once!
By the end of this session, you'll be well-versed in using sets for such tasks. Let’s dive in!
Introducing Methods to Implement
Here are the methods we need to implement in our enrollment system:
enroll(student: String, course: String): This method adds a student to a course. If the student is already enrolled, it does nothing.unenroll(student: String, course: String): Boolean: This method removes a student from a course. It returnstrueif the student was enrolled and has now been removed. Otherwise, it returnsfalse. If, after unenrolling the student, the course becomes empty, remove the course as well.isEnrolled(student: String, course: String): Boolean: This method checks if a student is enrolled in a course. It returnstrueif the student is enrolled andfalseotherwise.listStudents(course: String): List<String>: This method returns a list of all students enrolled in a given course. If no students are enrolled, it returns an empty list.
Let's look at how to implement each of these methods step-by-step.
Step 1: Define the Class
We'll start by defining our class and then add each method one by one.
First, we define our EnrollmentSystem class:
This code initializes an EnrollmentSystem class with a map named enrollments that maps courses to sets of students.
Step 2: Implement `enroll` Method
Next, we implement the enroll method:
Here, the enroll method checks if the course exists in the enrollments map. If it doesn't, it initializes a new set for that course using computeIfAbsent. Then, it adds the student to the set of students for that course.
