r/java • • Aug 03 '25

Teach Me the Craziest, Most Useful Java Features — NOT the Basic Stuff

I want to know the WILD, INSANELY PRACTICAL, "how the hell did I not know this earlier?" kind of Java stuff that only real devs who've been through production hell know.

Like I didn't know about modules recently

393 Upvotes

279 comments sorted by

View all comments

Show parent comment

55

u/GuyWithLag Aug 03 '25

Yes, this is a Java subreddit, but I love how concise this can be done in Kotlin:

enum class operation(private val op: (Double, Double) -> Double) { 
  ADD { a, b -> a + b },
  SUBTRACT { a, b -> a - b },
  MULTIPLY { a, b -> a * b },
  DIVIDE { a, b -> a / b },
  ;

  fun apply(x: Double, y: Double) = op(x, y)
}

25

u/Ok-Scheme-913 Aug 03 '25

As mentioned by others, this is storing a lambda instead of being a method on the instance directly.

Java could also do that:

enum Operation {
  ADD((a,b) -> a+b)
;

  Operation(BiFunction<Double, Double, Double> op) {
    this.op = op;
  }

  BiFunction<Double, Double, Double> op;
}

16

u/Dagske Aug 03 '25

Or use DoubleBinaryOperator rather than BiFunction<Double,Double,Double>. It's more concise and you avoid the costly cast.

5

u/GuyWithLag Aug 03 '25

Oh I know - I'd not do the lambda indirection in performance-sensitive code.

10

u/Efficient_Present436 Aug 03 '25

you can do this in java as well by having the function be a constructor argument instead of an overridable method, though it'd still be less verbose in kotlin

4

u/Masterflitzer Aug 03 '25

yeah i use it all the time in kotlin, didn't know java could do it similarly

6

u/GuyWithLag Aug 03 '25

Kotlin maps pretty well to the JVM (well, except for companion objects...), so it's only natural.

1

u/SleepingTabby Aug 10 '25

Java is slighly more verbose, but essentially the same thing

enum Operation {
  ADD((a, b) -> a + b),
  SUB((a, b) -> a - b),
  MUL((a, b) -> a * b),
  DIV((a, b) -> a / b);

  private final DoubleBinaryOperator op;

  Operation(DoubleBinaryOperator op) {
    this.op = op;
  }

  double apply(double x, double y) {
    return op.applyAsDouble(x, y);
  }
}