Chapters

Hide chapters

Functional Programming in Kotlin by Tutorials

First Edition · Android 12 · Kotlin 1.6 · IntelliJ IDEA 2022

Section I: Functional Programming Fundamentals

Section 1: 8 chapters
Show chapters Hide chapters

Appendix

Section 4: 13 chapters
Show chapters Hide chapters

A. Appendix A: Chapter 1 Exercise Solutions
Written by Massimo Carli

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Exercise 1.1

Implement the function sumInRange that sums the values in a List<String> within a given interval. The signature is:

 fun sumInRange(input: List<String>, range: IntRange): Int

Exercise 1.1 solution

A possible solution is the following:

fun sumInRange(input: List<String>, range: IntRange): Int = // 1
  input
    .filter(::isValidNumber) // 2
    .map(String::toInt) // 3
    .filter { it in range } // 4
    .sum() // 5
fun main() {
  println(sumInRange(listOf("1", "10", "a", "7", "ad2", "3"), 1..5))
}
4

Exercise 1.2

Implement chrono, which accepts a function of type () -> Unit as input and returns the time spent to run it. The signature is:

fun chrono(fn: () -> Unit): Long

Exercise 1.2 solution

A possible implementation for chrono is the following:

fun chrono(fn: () -> Unit): Long { // 1
  val start = System.currentTimeMillis() // 2
  fn() // 3
  return System.currentTimeMillis() - start // 4
}
fun main() {
  val waitOneSec = { Thread.sleep(1000) } // 1
  println(chrono(waitOneSec)) // 2
}
1005
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now