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:
Diego Moreira 2018-12-07 09:37:29 -03:00 committed by GitHub
commit 18ff18671b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 28 additions and 0 deletions

View File

@ -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()