Merge pull request #5853 from alimate/BAEL-2377
Added a simple Kotlin function for bytecode inspection as part of the Inline Functions tutorial.
This commit is contained in:
commit
18ff18671b
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.functions
|
||||
|
||||
import kotlin.random.Random
|
||||
|
||||
/**
|
||||
* An extension function on all collections to apply a function to all collection
|
||||
* elements.
|
||||
*/
|
||||
fun <T> Collection<T>.each(block: (T) -> Unit) {
|
||||
for (e in this) block(e)
|
||||
}
|
||||
|
||||
/**
|
||||
* In order to see the the JVM bytecode:
|
||||
* 1. Compile the Kotlin file using `kotlinc Inline.kt`
|
||||
* 2. Take a peek at the bytecode using the `javap -c InlineKt`
|
||||
*/
|
||||
fun main() {
|
||||
val numbers = listOf(1, 2, 3, 4, 5)
|
||||
val random = random()
|
||||
|
||||
numbers.each { println(random * it) } // capturing the random variable
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a random number.
|
||||
*/
|
||||
private fun random(): Int = Random.nextInt()
|
Loading…
Reference in New Issue