Reputation: 2904
I use simple java code for Future:
Future<Integer> futureTask = executor.submit(() -> {
System.out.println("I'm Callable task.");
return 1 + 1;
});
when I paste it to kotlin class it transforms to :
val futureTask = executor.submit {
println("I'm Callable task.")
1 + 1
}
but when I try to get a value as in Java class I`m got null instead number
val integ = futureTask.get()
when I write return as in java code my ide warns that return is not allowed here.
Full kotlin code is next:
fun main(args: Array<String>) {
val executor = Executors.newSingleThreadExecutor()
val futureTask = executor.submit {
println("I'm Callable task.")
1 + 1
}
println(futureTask.get())
executor.shutdown() }
Output:
I'm Callable task.
null
What is a right syntax for Future
?
Upvotes: 4
Views: 1802
Reputation: 3723
That is because there are two submit
methods in ExecutorService
and the wrong one is used.
<T> Future<T> submit(Callable<T> task);
Future<?> submit(Runnable task);
Your lambda function is translated to a Runnable instead of Callable. You can workaround this as following:
val futureTask = executor.submit(Callable {
println("I'm Callable task.")
1 + 1
})
Upvotes: 5