Figured it out.
Apparently this works:
val executor = Executors.newFixedThreadPool(10)
val service = MoreExecutors.listeningDecorator(executor)
val future = service.submit<Int> { 42 }
val transformed = Futures.transform(
future,
com.google.common.base.Function { it : Int? -> "[" + Integer.toString(it!!) + "]" },
executor)
Futures.addCallback(transformed, object : FutureCallback<String> {
override fun onSuccess(result: String?) { println("Success: " + result!!) }
override fun onFailure(t: Throwable) { t.printStackTrace() }
})
executor.shutdown()
A type declaration on a function argument (it: Int?) is essential, without this declaration, the code doesn’t compile.
Was difficult to figure out as the error message was complaining about a Function type, and apparently a guava’s Function was expected.
The code can be made even slightly more readable with a use of a typealias:
typealias GuavaFunction<I, O> = com.google.common.base.Function<I, O>
So the code becomes just this:
val transformed = Futures.transform(
future,
GuavaFunction { it : Int? -> "[" + Integer.toString(it!!) + "]" },
executor)
Yes, still, I wonder, is it possible to do it better, without an explicit indication that it’s a GuavaFunction, and without explicit argument type declaration in an anonymous function?