article banner

Functional Kotlin now with exercises

I previously announced that I introduced exercises to the Kotlin Essentials, now I am happy to announce that I introduced them as well to the Functional Kotlin book. Though, I must say, I am especially proud from exercises in this book. The range of topics gave me an amazing opportunity to make exercises that are both fun an amazing. So in this book, you will be asked to implement many multistep collection processings, or to optimize an existing one, to implement a DSL, to play with lambda expressions, to simplify a real-life service by using scope functions (let, also, apply, takeIf), to use context receivers, and much more. I am sure you will have a lot of fun.

About exercises

I did my best for each exercise to base only on what was already covered in the book, and to be and appropriate level for reader. Some exercises concentrate on practicing the knowledge presented in the preceding chapter. Like the exercise that asks to implement the same set of functions, but using different function literals: lambda expressions, anonymous functions, function references, bounded function references. Different exercises confront the reader with a real-life problem, like the exercise to implement collection processing to achieve a certain result. Many exercises leave the reader with useful knowledge, like they present ways how code can be optimized. Other exercises present an alternative ways how things can be done, like the exercise that asks reader to introduce scope functions to simplify a functional service class.

Here are some exercises in a form of articles:

The majority of exercises have starting code, sample usages, and unit tests. I located them in the project kotlin-exercises, that can be cloned and used as a starting point for each exercise. Solutions are presented on the last pages of the book.

If you are teaching Kotlin at a public school or a university, feel free to use my exercises on your course.

Sample exercise: Passing students list

Implement makePassingStudentsListText function to display a list of students who have got more than 15 points in the semester and a result of at least 50. Display them in a single string, presenting each student in a new line, in alphabetical order (sorting by surname, and for equals surnames by name), in the format: “{name} {surname}, {result}”

fun List<Student>.makePassingStudentsList(): String = TODO() data class Student( val name: String, val surname: String, val result: Double, val pointsInSemester: Int )

Starting code and unit tests can be found in the kotlin-exercises project on GitHub in the file functional/collections/PassingStudents.kt. You can clone this project and solve this exercise locally.

Ending

I hope those exercises will help readers' practice present a topic, and as a result, understand it on a deeper level. I believe this is a big step for making this book better.