如何模拟多参数副作用函数 [英] How to emulate a multi-parameter side-effect Function
问题描述
我想模仿以下界面:
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:
- 必须定义一个名为
Pair< T>
的类,它看起来很像Map.Entry< T,T>
带有更合适的getter名称(作为第二个问题:是否有像这样的Guava类型?)。 -
Void
返回类型总是很痛苦 - 拥有真正的void
签名会更好。
- One must define a class called
Pair<T>
, which looks a lot like aMap.Entry<T, T>
with more appropriate getter names (as a second question: is there a Guava type like this?). - The
Void
return type is always a pain - it would be better to have a genuinevoid
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屋!