Hello everyone. I ran into a small issue using `me...
# kontributors
z
Hello everyone. I ran into a small issue using
measureTimeMillis
. I need to run some code, whose return value needs to be captured (roughly like the following snippet)
Copy code
var result: T? = null
val time = measureTimeMillis { result = block() }
log.verbose("timing: $time")
return result!!
Declaring
result
as a nullable
var
(which implies the not-null-assertion in the end) seems unnecessary as
measureTimeMillis
will be inlined yielding roughly:
Copy code
val result: T
...
result = block()
...
which is perfectly valid. One possible solution is to create something like
measureTimeMillisWithResult
which returns the result and the timing. From my point of view a cleaner approach is to reuse the already existing
measureTimeMillis
for this, but augment it with
Copy code
contract {
    callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
which should give the compiler enough hints to deduce that there's just one assignment. While looking at it,
measureTimeMillis
could also be rewritten to delegate to
measureNanoTime
with some conversion, which could maybe fix https://youtrack.jetbrains.com/issue/KT-24431. Is it worth creating a PR for this?