【问题标题】:(Java) Is it possible to have a function return an operator?(Java)是否可以让函数返回运算符?
【发布时间】:2019-05-10 23:01:37
【问题描述】:

我想知道是否可以将运算符作为对象或类型返回。

这将用于解析二维坐标数组以确定两个多边形重叠的边界框。该函数的输出将确定 for 循环的布尔语句,因此算法可以根据多边形的运动方向从多边形的背面开始解析。

public <operator> function(int value){
    if(value < 0) {
        return >=;
    }
    return <=;
}

上面的语法显然是完全错误的,但我一直在寻找类似的东西。

我想使用类似的功能:

if(var1 function(value) var2)

这样的东西真的存在吗?如果没有,有没有其他方法可以在 >= 和

【问题讨论】:

标签: java operators


【解决方案1】:

很遗憾,您不能返回运算符。根据JLS关于:

return Expressionopt;

表达式必须表示某个类型 T 的变量或值,否则会发生编译时错误。

由于运算符不是变量或值,因此不能返回它。

为什么不让方法做比较:

public boolean function(int value, int num1, int num2){
    if(value < 0) {
        return num1 >= num2;
    }
    return num1 <= num2;
}

然后称它为:

if(function(value, var1, var2))

【讨论】:

    【解决方案2】:

    您可以返回BiPredicate

    public BiPredicate<Integer, Integer> function(int value) {
        if(value < 0) {
            return (a, b) -> a >= b;
        }
        return (a, b) -> a <= b;
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用 Java 8 的功能接口。

      由于您需要 2 个操作数和一个布尔结果,您可以简单地使用 BiPredicate,但由于您希望 2 个操作数属于同一类型,因此您需要重复该类型,因此您可以创建一个新的功能界面,例如命名为BinaryPredicate:

      interface BinaryPredicate<T> extends BiPredicate<T, T> {
          // nothing to add
      }
      

      那么你的方法可能是,例如像这样,如果您希望操作数是实现Comparable 的类型:

      public static <T extends Comparable<T>> BinaryPredicate<T> objectOperator(int value){
          if (value < 0)
              return (a, b) -> a.compareTo(b) >= 0;
          return (a, b) -> a.compareTo(b) <= 0;
      }
      

      如果您希望操作数为 int 值,则可以改为创建:

      interface IntBinaryPredicate {
          boolean test(int a, int b);
      }
      

      然后像这样做你的方法:

      public static IntBinaryPredicate intOperator(int value){
          if (value < 0)
              return (a, b) -> a >= b;
          return (a, b) -> a <= b;
      }
      

      您将如何使用它们:

      BinaryPredicate<String> stringOp = objectOperator(1);
      if (stringOp.test("Foo", "Bar"))
      
      IntBinaryPredicate intOp = intOperator(1);
      if (intOp.test(13, 42))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-11
        • 2020-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-25
        • 1970-01-01
        相关资源
        最近更新 更多