I have an object that's only allowed to be touched...
# announcements
k
I have an object that's only allowed to be touched on a certain thread. My idea is to pass a higher-order callback that receives a function which takes the object on the correct thread and returns a
Future
of the value it returns. The code looks like this:
Copy code
class Foo(private val executorCallback: ((GraphDatabaseService) -> Any?) -> Future<*>) { ... }

// instantiation site
private val executor: ExecutorService
private val db: GraphDatabaseService

executorCallback = { executor.submit { it(db) } }
My problem is that this is not type-safe. The future will always have the type of what the passed function will return but I can't express this. The best I can come up with is a wrapper function
Copy code
@Suppress("UNCHECKED_CAST")
private fun <T> submit(f: (GraphDatabaseService) -> T): Future<T> {
    return executorCallback(f) as Future<T>
}