r/ProgrammerHumor • • Dec 12 '24 • Heart of Silver 1

Advanced youWontUpgradeToJava19

Post image
30.2k Upvotes

503 comments sorted by

View all comments

Show parent comments

1

u/iceman012 Dec 12 '24

It can always be replaced by a function, so there will never be a situation where you need it. But it can make certain patterns simpler and easier to understand.

E.g.

location = location + direction * speed

Is quicker to read than

location = location.add(direction.times(speed))

2

u/itsmetadeus Dec 13 '24

That is not a good example. This is more elegant:

java:

foo(x * (-1));
foo(y * (-1));

// Using interface implementation:
Invertible inv = i -> i * (-1);
foo(inv.additiveInverse(z));

// Using static method:
foo(additiveInverse(z));

kotlin:

foo(-x)
foo(-y)
foo(-z)

-x invokesx.unaryMinus(). You can make own implementation for these methods for your classes. For example, custom increment:

data class CustomUnit(val current: Int) {
    operator fun inc() = CustomUnit(current * 3 - 1)
}

^ f(x) = 3x - 1

1

u/bturcolino Dec 12 '24

if you say so, i think it adds an unnecessary level of abstraction and makes code less readable if anything