Thursday, 23 October 2025

No "new" keyword in Kotlin

So I was wondering what my opinion is about that.

I don't like it a lot, as now it seems like calling a constructor looks similar to calling a method.

The only difference that's visible is that the constructor begins with a capital, and then only if you properly follow the coding style guidelines.

I noticed that where Java prefers clarity of purpose, Kotlin prefers brevity (and sacrifices clarity for this).

In Java the "new" keyword does a lot of heavy lifting, that is not part of the constructor. The constructor merely sets the internal structure of an object-to-be to appropriate values. The responsibility of actually making the object, registering it in de Heap, doing the pointer bits, is indicated by the new keyword.

What are your opinions?

References

Reddit - Is keyword new redundant?
https://www.reddit.com/r/java/comments/1n0m7cg/is_keyword_new_redundant/
Kotlin Documentation - Classes
https://kotlinlang.org/docs/classes.html

Thursday, 16 October 2025

Bridge Methods in Java

In Java, Generics are erased ("type erasure") at compile time. This concept introduces a problem where an abstract super class containing generics <T> will be compiled to abstract super class with "Object".

In which case implementation of this abstract class with specific Generics (say for example <String>) will cause the compiler to create Bridge Methods, in this case the someMethod(Object o) will call someMethod(String o) with an appropriate cast.

Reference [1] and [2] has a much better explanation

You won't find it in the JLS, as it is an implementation detail. But interesting none the less.

References

[1] Medium - Bridge Methods in Java
https://medium.com/@rohitsingh341/bridge-methods-in-java-21a9d06b6b1b
[2] The Java Tutorials - Effects of Type Erasure and Bridge Methods
https://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html

Monday, 6 October 2025

Optional.or

Was working on something, and I wanted to combine two optionals. In my case, I know that only one of the two will be present (or none), so combining them would be nice.

I'm not a big fan of using .ifPresent() and .get() combos. So, let's try streams.

Using streams, this looks something like:

Luckily we have a Optional.or() nowadays (Since Java 9), that I haven't used before.

It looks a lot better:

The awesome part (which is not shown in the example above) is that the or() accepts a Supplier, which means the Supplier will not be called if a value is present in the first Optional.

This is similar to the short-circuit evaluation1 present in the || operator of the common if-statement.

References

[1] Wikipedia - Short-circuit evaluation
https://en.wikipedia.org/wiki/Short-circuit_evaluation
[2] Baeldung - Guide To Java Optional
https://www.baeldung.com/java-optional
[3] Combine two Java Optionals
https://www.agalera.eu/combine-two-optionals/