Inline function in Kotlin

Level 4185 keystrokes

An inline function's body and its lambda argument are copied into the call site, so no function object is created for the lambda. measureTime runs the block and prints the elapsed milliseconds, which vary from run to run (often 0ms for such a small block).

Kotlin code

// inline copies this body and the lambda into the caller, avoiding a lambda object
1inline fun measureTime(block: () -> Unit) {
// Record the start time in milliseconds
2 val start = System.currentTimeMillis()
// Run the code that was passed in
3 block()
// Print the elapsed time; the number varies between runs
4 println("Time: ${System.currentTimeMillis() - start}ms")
5}
6
// Prints Running, then a time such as Time: 0ms
7measureTime { println("Running") }

Output

Running
Time: 0ms
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.

  • (× 7
  • )× 7
  • "× 4
  • {× 3
  • }× 3
  • -× 2
  • :× 2
  • .× 2
  • =× 1
  • >× 1

More Kotlin examples at level 4

← Kotlin typing practice