Data transformation with map and flatMap
The support for declarative data mapping operations is one of the basic and most powerful features in the functional data-processing domain. Often, when working with data, we need to transform a collection of a specific type into another type. It's also a common scenario to generate a list of objects from each element of a collection and to merge all of those new objects in a target collection together. Those are the use cases where the map()
and flatMap()
extension functions help.
In this recipe, we are going to use both of them to implement a mapping data transformation. Let's imagine we are working on the part of the system responsible for managing university department lectures. We are given the following types:
class Course(val name: String, val lecturer: Lecturer, val isPaid: Boolean = false) class Student(val name: String, val courses: List<Course>) class Lecturer(val name: String)
We also have a getStudents(): List<Student>
function...