如何转换lambda方法参数? [英] How to cast lambda method parameters?

查看:131
本文介绍了如何转换lambda方法参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的lambda表达式.我想问的是是否有任何简单的方法或最佳实践来铸造方法参数?

I have a lambda expression like below. What I want to ask is Is there any easy way or best practice for casting method parameter?

        results.forEach(
            (result) ->
            {
                ((JSONObject)result).put("test", "test"); 
                ((JSONObject)result).put("time", System.currentTimeMillis());  
                otherList.add(((JSONObject)result));
            }
    );

当我尝试更改输入类型时

When I try to change input type like

(JSONObject result) ->

我遇到了错误;

incompatible types: Consumer<JSONObject> cannot be converted to Consumer<? super Object>

推荐答案

该错误消息向您说明,从编译器的角度来看,从技术上讲,您的列表可能包含不属于类JSONObject的元素.因此,您不能在此处使用Consumer<JSONObject>. lambda (JSONObject result) -> ...实际上 是这样的不兼容的使用者.

The error message explains to you that your list technically–from the compiler's perspective–may contain elements that are not of class JSONObject. Thus you cannot use a Consumer<JSONObject> here. The lambda (JSONObject result) -> ... actually is such an incompatible consumer.

假设您无法控制results的元素类型,则可以在使用元素之前将它们映射到正确的类型.如果您期望除JSONObject元素以外的任何内容,则可以使用filter()方法来省略所有不兼容的元素,而仅处理JSONObject实例.

Assuming you have no control over the element type of results you might just map your elements to the correct type before consuming them. In case you expect anything other than only JSONObject elements, you might use the filter() method to omit all incompatible elements and only process the JSONObject instances.

results.filter(JSONObject.class::isInstance) // only needed if you expect non JSONObject elements, too
       .map(result -> (JSONObject) result)
       .forEach(result -> {
         result.put("test", "test"); 
         result.put("time", System.currentTimeMillis());  
         otherList.add(((JSONObject)result));
       });

这篇关于如何转换lambda方法参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆