What does the -> <- operator do?

后端 未结 1 1788
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-31 13:02

I recently came upon the following code:

IntPredicate neg = x -> x <- x;

What is this, some sort of reverse double lambda?

相关标签:
1条回答
  • 2021-01-31 13:46

    There is no -> <- operator. That first -> is just lambda syntax, as introduced in Java 8, and that second <- is a misleading concatenation of 'smaller than' < and 'unary minus' -.

    You can read it as IntPredicate neg = (x) -> (x < (-x));, i.e. it tests whether x is smaller than -x, which is the case for all (well, most) negative numbers, hence the name neg.

    IntPredicate neg = x -> x <- x;
    System.out.println(neg.test(4));   // false
    System.out.println(neg.test(0));   // false
    System.out.println(neg.test(-4));  // true
    

    Just for completeness: This test is not only (intentionally?) hard to understand, but -- as pointed out in the comments -- it also fails for Integer.MIN_VALUE (which is ==-Integer.MIN_VALUE). Instead, you should probably just use the much simpler IntPredicate neg = x -> (x < 0);.

    0 讨论(0)
提交回复
热议问题