Sorry for the crappy title but not sure how to summarize what I’m trying to say.
So I have this inline function that measures the execution time for a block of code:
inline fun <T> measureTime(message: String? = null, printMessage: Boolean = true, block: () -> T): Pair<Long, T> { val start = System.nanoTime() val ret = block() val duration = System.nanoTime() - start if (printMessage) { if (message == null) { println("Took $duration millis") } else { println("$message: Took $duration nanos (${duration / 1e6} millis)") } } return Pair(duration, ret) }
And here’s an example of a function that’s using this:
private fun getShortestPathInternal(rocks: List<MapEntity.Rock>): PathSequence? { measureTime("time it takes to get entities") { val allEntitiesExceptRocks = getAllEntitiesExceptRocks() val start = allEntitiesExceptRocks.first { it is MapEntity.Start } as MapEntity.Start val finish = allEntitiesExceptRocks.first { it is MapEntity.Finish } as MapEntity.Finish val checkpoints = allEntitiesExceptRocks.filterIsInstance<MapEntity.CheckPoint>() .sortedBy { it.sequenceNumber }.toList() val teleportIns = allEntitiesExceptRocks.filterIsInstance<MapEntity.TeleportIn>().groupBy { it.sequenceNumber } val teleportOuts = allEntitiesExceptRocks.filterIsInstance<MapEntity.TeleportOut>().groupBy { it.sequenceNumber } } // Error: Missing start, finish, checkpoints, etc return measureTime("time it took to get path") { searcher.getShortestPath( width, height, start, finish, checkpoints, teleportIns.map { TeleportPair(it.value.first(), teleportOuts[it.key]!!.first()) }, rocks ) }.second }
So the problem I’m experiencing is that if I wrap the initialization of the start, finish, checkpoints, etc into the measureTime function, then those variables aren’t available outside the scope of the lambda.
I was wondering if there’s a way to make this work so that the variables would be accessible outside the scope?
submitted by /u/IllTryToReadComments
[link] [comments]