Inline function returning a value in Kotlin

Level 5266 keystrokes

inline copies measureTime and its lambda into the call site, avoiding a function object. It returns the elapsed milliseconds, which vary between runs. sum starts at 0L, a Long, because the total 500000500000 is too large for an Int.

Kotlin code

// inline: the body and the lambda are copied into the caller; returns a Long
1inline fun measureTime(block: () -> Unit): Long {
// Record the start time in milliseconds
2 val start = System.currentTimeMillis()
// Run the measured code
3 block()
// Return the elapsed milliseconds
4 return System.currentTimeMillis() - start
5}
6
// Pass the code to measure as a trailing lambda
7val elapsed = measureTime {
// 0L makes sum a Long (64-bit); an Int would overflow past 2147483647
8 var sum = 0L
// Adds 1 to 1,000,000; Long + Int gives a Long, so the total fits
9 for (i in 1..1000000) sum += i
// Prints Sum: 500000500000
10 println("Sum: $sum")
11}
// Print the elapsed time, for example Time: 15ms; the number varies between runs
12println("Time: ${elapsed}ms")

Output

Sum: 500000500000
Time: 15ms
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • (× 8
  • )× 8
  • :× 4
  • .× 4
  • "× 4
  • =× 4
  • {× 3
  • }× 3
  • -× 2
  • $× 2

More Kotlin examples at level 5

← Kotlin typing practice