消除 lambda 中功能接口的歧义
Disambiguate functional interface in lambda
假设这样:
ExecutorService service = ...;
// somewhere in the code the executorService is used this way:
service.submit(() -> { ... });
lambda 表达式默认为 Callable
。
有没有办法让它实例化一个 Runnable
呢?
感谢您的帮助。
您可以将其声明为 Runnable,或使用强制转换:
Runnable r = () -> { ... };
executorService.submit(r);
或
executorService.submit((Runnable) () -> { ... });
service.submit((Runnable) () -> {
...
});
你的前提是错误的。此调用不默认为 Callable
。选择是通过 lambda 表达式的形状进行的,即它是否 returns 一个值:
ExecutorService service = null;
// somewhere in the code the executorService is used this way:
// invokes submit(Runnable)
service.submit(() -> { });
// invokes submit(Runnable)
service.submit(() -> { return; });
// invokes submit(Callable)
service.submit(() -> "foo");
// invokes submit(Callable)
service.submit(() -> { return "foo"; });
// in case you really need disambiguation: invokes submit(Runnable,null)
service.submit(() -> { throw new RuntimeException(); }, null);
// dito (ignoring the returned value)
service.submit(this::toString, null);
请注意,如果您不需要返回的 Future
,您可以简单地使用 execute(Runnable)
直接入队 Runnable
,而不是将其包装在 [=15] =].
Callable
和 Runnable
在签名方面的区别在于 Callable
返回一个值,而 Runnable
没有。
所以 () -> { }
是 Runnable
而例如() -> ""
是 Callable
.
假设这样:
ExecutorService service = ...;
// somewhere in the code the executorService is used this way:
service.submit(() -> { ... });
lambda 表达式默认为 Callable
。
有没有办法让它实例化一个 Runnable
呢?
感谢您的帮助。
您可以将其声明为 Runnable,或使用强制转换:
Runnable r = () -> { ... };
executorService.submit(r);
或
executorService.submit((Runnable) () -> { ... });
service.submit((Runnable) () -> {
...
});
你的前提是错误的。此调用不默认为 Callable
。选择是通过 lambda 表达式的形状进行的,即它是否 returns 一个值:
ExecutorService service = null;
// somewhere in the code the executorService is used this way:
// invokes submit(Runnable)
service.submit(() -> { });
// invokes submit(Runnable)
service.submit(() -> { return; });
// invokes submit(Callable)
service.submit(() -> "foo");
// invokes submit(Callable)
service.submit(() -> { return "foo"; });
// in case you really need disambiguation: invokes submit(Runnable,null)
service.submit(() -> { throw new RuntimeException(); }, null);
// dito (ignoring the returned value)
service.submit(this::toString, null);
请注意,如果您不需要返回的 Future
,您可以简单地使用 execute(Runnable)
直接入队 Runnable
,而不是将其包装在 [=15] =].
Callable
和 Runnable
在签名方面的区别在于 Callable
返回一个值,而 Runnable
没有。
所以 () -> { }
是 Runnable
而例如() -> ""
是 Callable
.