gpt4 book ai didi

java - 在@FunctionalInterface 中处理可变参数的更简洁方法?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:02:00 24 4
gpt4 key购买 nike

考虑这个接口(interface):

@FunctionalInterface
public interface ThrowingFunction<T, R>
{
R tryApply(T t)
throws Throwable;
}

这个类:

public final class Wrapper<T, R>
{
private final ThrowingFunction<T, R> f;

public Wrapper(final ThrowingFunction<T, R> f)
{
this.f = f;
}
}

有了这些,我可以写:

final ThrowingFunction<Path, Path> f = Path::toRealPath;

new Wrapper(f);

但我不能写:

new Wrapper(Path::toRealPath);

问题是由于the method prototype .它可以LinkOption... 作为参数。

然而,编译器能够“强制”此处的方法引用。我想出的唯一模仿这个的方法是彻头彻尾的骇人听闻:

@FunctionalInterface
public interface ThrowingFunction<T, R>
{
R tryApply(T t)
throws Throwable;

@FunctionalInterface
interface WithVarags<T, V, R>
extends ThrowingFunction<T, R>
{
R tryApplyWithVarargs(T t, V... ignored)
throws Throwable;

@Override
default R tryApply(T t)
throws Throwable
{
return tryApplyWithVarargs(t);
}
}
}

然后向Wrapper 添加一个新的构造函数:

public <V> Wrapper(
final ThrowingFunction.WithVarags<T, V, R> function)
{
this.function = function;
}

有没有更简洁的方法来做到这一点?也就是说,在这种情况下我可以“像编译器一样”吗?

最佳答案

您可以在实例化时指定 Wrapper 的类型。

new Wrapper<Path, Path>(Path::toRealPath);

Wrapper<Path, Path> wrapper = new Wrapper<>(Path::toRealPath);

我认为这与可变参数无关。通过指定类型,您还告诉编译器“忽略”varargs 参数。


请注意,我看到您也可以“忽略”同一函数的返回类型:

ThrowingBiConsumer<Path, LinkOption[]> biConsumer =  Path::toRealPath;
new Wrapper<Path, LinkOption[]>(Path::toRealPath);


public interface ThrowingBiConsumer<T, U> {
void accept(T t, U u) throws Throwable;
}

关于java - 在@FunctionalInterface 中处理可变参数的更简洁方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27723325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com