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 Long1inline fun measureTime(block: () -> Unit): Long { // Record the start time in milliseconds2 val start = System.currentTimeMillis() // Run the measured code3 block() // Return the elapsed milliseconds4 return System.currentTimeMillis() - start5}6 // Pass the code to measure as a trailing lambda7val elapsed = measureTime { // 0L makes sum a Long (64-bit); an Int would overflow past 21474836478 var sum = 0L // Adds 1 to 1,000,000; Long + Int gives a Long, so the total fits9 for (i in 1..1000000) sum += i // Prints Sum: 50000050000010 println("Sum: $sum")11}// Print the elapsed time, for example Time: 15ms; the number varies between runs12println("Time: ${elapsed}ms")Output
Sum: 500000500000 Time: 15ms
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