如何模拟多参数副作用函数 [英] How to emulate a multi-parameter side-effect Function

查看:93
本文介绍了如何模拟多参数副作用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想模仿以下界面:

interface MultiSideEffectFunction<T> {
    void action(T first, T second);
}

(这将使我免于引入新界面)

(it would save me from having to introduce a new interface)

有没有首选的番石榴方法来做这件事?

is there a preferred Guava approach to doing this?

注意:我想用

Function<Pair<T>, Void>

但有两个问题使得创建新界面更为可取:

but there are two problems which makes the creation of a new interface preferable:


  1. 必须定义一个名为 Pair< T> 的类,它看起来很像 Map.Entry< T,T> 带有更合适的getter名称(作为第二个问题:是否有像这样的Guava类型?)。

  2. Void 返回类型总是很痛苦 - 拥有真正的 void 签名会更好。

  1. One must define a class called Pair<T>, which looks a lot like a Map.Entry<T, T> with more appropriate getter names (as a second question: is there a Guava type like this?).
  2. The Void return type is always a pain - it would be better to have a genuine void signature.


推荐答案

这里的番石榴贡献者。

首选番石榴方法是编写自己的界面。

The preferred Guava approach is to write your own interface.

特别是,使用功能 ; 函数只应在函数没有副作用时使用。

In particular, do not use Function; Function should only be used when the function doesn't have side effects.

Guava故意缺少类型;我们建议您在需要配对时,创建自己的类,将有用的名称附加到两个值,而不是完全没有信息的第一和第二。 (原型示例用于GPS坐标;名为 LatLong 的类比对< Double,Double> 。)

Guava deliberately lacks a Pair type; we advise that any time you need a pair, you create your own class that attaches useful names to the two values, rather than the utterly uninformative "first" and "second". (The prototypical example is for GPS coordinates; a class entitled LatLong is much more informative than a Pair<Double, Double>.)

这篇关于如何模拟多参数副作用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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