在消费者表达式中返回 Method 值 [英] Returning Method value inside a Consumer expression
问题描述
我正在尝试在方法中返回一个布尔值,并且我正在使用消费者函数.有没有办法直接在 Consumer 表达式中返回该值?
I'm trying to return a boolean inside a Method and i'm using a consumer function. Is there any way to return that value directly inside that Consumer expression?
代码如下:
private static boolean uuidExists(UUID uuid) {
MySQL.getResult("", rs -> {
try {
if(rs.next()){
return rs.getString("UUID") != null;
}
} catch (SQLException e) {
}
});
return false;
}
我知道我可以创建一个布尔值并更改该值,但我不想这样做.
I know that i could create a boolean and change that value but i do not wanna do that.
获取结果代码:
public static void getResult(String qry, Consumer<ResultSet> consumer){
new BukkitRunnable() {
@Override
public void run() {
if(isConnected()) {
consumer.accept(Warpixel.getWarpixel().getStats().getResult(qry));
return;
}
consumer.accept(null);
}
}.runTaskAsynchronously(Bedwars.getMain());
}
推荐答案
不,这是不可能的.lambda 表达式是 Consumer.accept
的实现,因此无法返回值,因为该方法无效.
No, it's not possible. The lambda expression is an implementation of Consumer.accept
and can therefore not return a value because that method is void.
我知道我可以创建一个布尔值并更改该值,但我不想这样做.
I know that i could create a boolean and change that value but i do not wanna do that.
也不是.在 lambda 表达式中,您只能引用最终的局部变量(使其本质上是不可能的).您将不得不使用其他技术(例如可修改的参考对象)来解决此限制.
Not really either. In a lambda expression, you may only reference local variables that are final (making it inherently impossible). You would have to use other techniques (such as a modifiable reference object) to go around this limitation.
可以建议的一种方法是在此处使用未来:
An approach that could be suggested is to use a future here:
CompletableFuture<Boolean> future = new CompletableFuture<Boolean>();
MySQL.getResult("", rs -> {
try {
if(rs.next()){
future.complete(rs.getString("UUID") != null);
}
} catch (SQLException e) {
//handle exception
}
future.complete(false); //mind this default value
});
return future.join(); //this will block until the `Consumer` calls complete()
需要注意的是,这是一种阻止异步执行的方法.
It's important to note that this is a way to block an execution meant to be asynchronous.
这篇关于在消费者表达式中返回 Method 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!