aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/mcprepack/WorkContext.kt
diff options
context:
space:
mode:
authornea <nea@nea.moe>2023-03-10 21:52:31 +0100
committernea <nea@nea.moe>2023-03-10 21:52:31 +0100
commitf3f54f463feb714b4b875a00fa9b92413acd67fd (patch)
treefd0c0ab60c098ecafdf94b283453022d75a06f26 /src/main/kotlin/mcprepack/WorkContext.kt
parent620b8c495de8c342785eff0d123bf8058080f6b8 (diff)
downloadmcprepack-f3f54f463feb714b4b875a00fa9b92413acd67fd.tar.gz
mcprepack-f3f54f463feb714b4b875a00fa9b92413acd67fd.tar.bz2
mcprepack-f3f54f463feb714b4b875a00fa9b92413acd67fd.zip
laziness
Diffstat (limited to 'src/main/kotlin/mcprepack/WorkContext.kt')
-rw-r--r--src/main/kotlin/mcprepack/WorkContext.kt20
1 files changed, 16 insertions, 4 deletions
diff --git a/src/main/kotlin/mcprepack/WorkContext.kt b/src/main/kotlin/mcprepack/WorkContext.kt
index 74e929d..ee9cbd9 100644
--- a/src/main/kotlin/mcprepack/WorkContext.kt
+++ b/src/main/kotlin/mcprepack/WorkContext.kt
@@ -5,6 +5,8 @@ import java.net.URL
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
+import kotlin.properties.ReadOnlyProperty
+import kotlin.reflect.KProperty
import kotlin.system.exitProcess
import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
@@ -69,20 +71,30 @@ object WorkContext {
}
+class Potential<T>(compute: () -> T) : ReadOnlyProperty<Any?, T> {
+ private val t by lazy { compute() }
+ override fun getValue(thisRef: Any?, property: KProperty<*>): T = t
+ fun get() = t
+
+ fun executeNow() {
+ get()
+ }
+}
+
@OptIn(ExperimentalTime::class)
-fun <T> lifecycle(name: String, block: () -> T): T {
+fun <T> lifecycle(name: String, block: () -> T): Potential<T> = Potential {
var x: T
println("> $name")
val time = measureTime {
x = block()
}
println("> $name done. Took $time")
- return x
+ return@Potential x
}
@OptIn(ExperimentalTime::class)
-fun <T : Any> lifecycleNonNull(name: String, block: () -> T?): T {
+fun <T : Any> lifecycleNonNull(name: String, block: () -> T?): Potential<T> = Potential {
var x: T?
println("> $name")
val time = measureTime {
@@ -93,5 +105,5 @@ fun <T : Any> lifecycleNonNull(name: String, block: () -> T?): T {
exitProcess(1)
}
println("> $name done. Took $time")
- return x as T
+ return@Potential x as T
}