Mono 带有 if 语句

huangapple go评论62阅读模式
英文:

Mono<Boolean> with if statement

问题

I have Mono<Boolean>. How can I use it in an if statement?

英文:
public void func() {
  Mono&lt;Boolean&gt; monoBool = ...
  if (!monoBool) {
     throw new CustomException();
  }
}

I have Mono<Boolean>. How i can use him in if statement?

答案1

得分: 1

! 运算符基本上适用于布尔表达式。

因此,显然,

boolean someBool = ...
if (!someBool)

可以工作。当变量的类型为 Boolean 时,同样适用,因为引用类型可以轻松地装箱到原始类型。

但没有规则告诉 Java 如何将一些通用类(不管它使用的通用类型是什么)转换为布尔值。因此 !monoBol 不是有效的 Java 代码。

但在你的情况下,Mono 实例可能会向你提供一个(或多个)布尔值。

换句话说:教育自己如何使用该类,请参阅此处的示例。

英文:

The ! operator basically works for boolean expressions.

So obviously,

boolean someBool = ...
if (!someBool) 

works. The same works when the variable is of type Boolean, as the reference type can be boxed to the primitive type easily.

But there is no rule that would tell java how to turn some generic class (no matter the generic type it is using) into boolean. Therefore !monoBol isn't valid java code.

But, in your case, that Mono instance might provide one (or more) Boolean values to you.

In other words: educate yourself how to use that class, see here for example.

答案2

得分: 0

你可以使用Mono的java.util.function.Supplier参数方法。

例如:

boolean flag = true;
Mono<Boolean> monoExample = Mono.fromSupplier(() -> {
   if(flag) {
      throw new RuntimeException();
   }
   return flag;
});
英文:

You can use import java.util.function.Supplier argument method of Mono.

For Example:

boolean flag = true;
Mono&lt;Boolean&gt; monoExample = Mono.fromSupplier(()-&gt;{
   if(flag) {
      throw new RuntimeException();
   }
   return flag;
});

huangapple
  • 本文由 发表于 2020年8月13日 19:20:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63394050.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定