stoyicker
10/26/2023, 1:17 PMprivate fun <T> runInTheFutureButAlsoWaitForResult(block: Foo.() -> T): T {
var ret: T? = null
var done = false
val condition = reentrantLock.newCondition()
someOtherThread.runAtSomePointInTheFuture {
ret = delegate.block()
done = true
reentrantLock.withLock { condition.signal() }
}
reentrantLock.withLock {
while (!done) {
condition.await()
}
}
return ret as T
}
While this does work at runtime for both cases in which T is nullable and non-nullable, casting ret to T is marked as unsafe, which does make sense, but if I define ret as type T, I can't assign null to it, which makes sense too, but I also can't assign anything else because I don't know what T is so I can't instantiate it. Therefore, I could try to make it lateinit, but mind you, lateinit can't be used with types whose upper bound is nullable, as is the case implicitly for T. Is there a way to write this code "correctly"?hho
10/26/2023, 1:33 PMfun <T> runInTheFutureButAlsoWaitForResult(block: Foo.() -> T?): T? {
…
return ret
}
stoyicker
10/26/2023, 1:36 PMret
ascii
10/26/2023, 2:09 PMstoyicker
10/26/2023, 2:11 PMDaniel Pitts
11/08/2023, 2:02 AMunsafe cast
complaint.delegate.block()
throws an exception.stoyicker
11/08/2023, 9:02 AM