无法使用Lambda表达式创建ThreadLocal类

时间:2018-10-16 15:45:35

标签: java java-8

我有以下代码

      ThreadLocal<Map<String, Service<Request, Response>>> connectinonMapThread = new ThreadLocal<Map<String, Service<Request, Response>>>() {
        @Override
        protected Map<String, Service<Request, Response>> initialValue() {
            return new HashMap<String, Service<Request, Response>>();
        }
    };

我想使用如下所示的lambda表达式编写它-

ThreadLocal<Map<String, Service<Request, Response>>> connectinonMapThread2 = new ThreadLocal<Map<String, Service<Request, Response>>>(() -> new HashMap<String, Service<Request, Response>>());

我尝试了另一个。

ThreadLocal<Map<String, Service<Request, Response>>> connectinonMapThread2 = initialValue() -> {

            return new HashMap<String, Service<Request, Response>>();
    };

但是我遇到编译错误。但是IntelliJ Idea建议这可以写为lambda表达式。

Intellij Idea Suggestion

1 个答案:

答案 0 :(得分:1)

magic

您试图将ThreadLocal<Map<String, Service<Request, Response>>> test = ThreadLocal.withInitial(HashMap::new); 表达式分配给非功能性接口,这将不起作用。幸运的是,lambda通过ThreadLocal方法为Supplier提供了一个选项