Skip to content

Commit 18ff186

Browse files
Merge pull request eugenp#5853 from alimate/BAEL-2377
Added a simple Kotlin function for bytecode inspection as part of the Inline Functions tutorial.
2 parents 9a0eab7 + 7f5789c commit 18ff186

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

  • core-kotlin/src/main/kotlin/com/baeldung/functions
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.baeldung.functions
2+
3+
import kotlin.random.Random
4+
5+
/**
6+
* An extension function on all collections to apply a function to all collection
7+
* elements.
8+
*/
9+
fun <T> Collection<T>.each(block: (T) -> Unit) {
10+
for (e in this) block(e)
11+
}
12+
13+
/**
14+
* In order to see the the JVM bytecode:
15+
* 1. Compile the Kotlin file using `kotlinc Inline.kt`
16+
* 2. Take a peek at the bytecode using the `javap -c InlineKt`
17+
*/
18+
fun main() {
19+
val numbers = listOf(1, 2, 3, 4, 5)
20+
val random = random()
21+
22+
numbers.each { println(random * it) } // capturing the random variable
23+
}
24+
25+
/**
26+
* Generates a random number.
27+
*/
28+
private fun random(): Int = Random.nextInt()

0 commit comments

Comments
 (0)