具有 void 返回类型且不带输入参数的 Function 的数据类型

问题描述 投票:0回答:2

我无法弄清楚这些函数的返回类型是什么

fooBar()
barFoo()
在 Java 中并收到以下错误。

import java.util.function.Function;

class FooBar {
  private void foo() {
  }

  private void bar(String s) {
  }

  public FunctionalInterface fooBar() {
    return this::foo;// The type of foo() from the type FooBar is void, this is incompatible with the
                     // descriptor's return type: Class<? extends Annotation>
  }

  public Function<String, Void> barfoo() {
    return this::bar;// The type of bar(String) from the type FooBar is void, this is incompatible
                     // with the descriptor's return type: Void
  }
}

有什么方法可以返回这些函数,以便它们可以被其他函数使用吗?

将返回类型设置为

FuncionalInterface
没有帮助。 将返回类型设置为
Void
,但它与
void

不兼容

谢谢!

java function void return-type
2个回答
0
投票

A

Function
有一个
<T,R>
泛型类型,您正在寻找
Runnable
void
void
函数)和
Consumer<T>
void
T
函数)。就像,

public Runnable fooBar() {
    return this::foo;
}

public Consumer<String> bar() {
    return this::bar;
}

0
投票

存在与

void f()
void f(String a)
匹配的类型。它们分别是
Runnable
Consumer<String>

所以你的代码变成:

import java.util.function.Consumer;

class FooBar {
    private void foo() {
    }

    private void bar(String s) {
    }

    public Runnable fooBar() {
        return this::foo;
    }

    public Consumer<String> barfoo() {
        return this::bar;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.