Have you thought about Kotlin equivalents in Java? In this article, we will decompile the most common Kotlin features to Java and check their comparisons. Also, this article is going to be a cheat sheet for interviewees :). So let's check all of them.
Update: Sealed class, Data class, Object, suspend functions are added.
By default, classes and functions in Kotlin are final. So, you can’t extend classeswithout an open modifier behind them.
Nested classes without an inner modifier are static. Here, the Programmer class is final and static. For the Gamer class, the inner modifier has been used. So, we cannot create an instance of Gamer class without having an instance of Human class.
val programmer = Human.Programmer()
val gamer = Human().Gamer()
We are aware of objects in Kotlin are singleton. So, this is the reason why they are singleton.
Here, we can only say WOW!
A data class, by default, has copy, toString, hashCode, and equals functions. With data class, we don’t need to implement these functions ourselves.
Everything that we write out of classes in a Kotlin file will be wrapped with a class that the name of the class is [fileName+Kt]. Also, to have accessibility to them, they are going static.
Anonymous Object Kotlin
The decompilation of an interface that has a function with a default body; is an interface with a static class that has the default function.
For anonymous classes, if you change the interface to an abstract class, the decompilation output won’t change.
Suspend functions are not void, they are functions with Object type that they get a kotlin.coroutines.Continuation as a parameter.
After the decompilation, the extension function will convert to a function with at least a parameter with class type.
Document: Inline functions
So, what happens if we add a “noinline” modifier before a parameter? The noinline modifier will ignore the inline behavior for that parameter.
Kotlin has different scope functions, such as let, apply, also, etc. All of them use a specific structure for decompilation. Check the let and apply decompiled code.
The let with null safety:
Null-safety added a condition to check the object that is null or not.
Depends on the delegation logic, the implementation is different. I cannot add them here, and knowing their decompilation is not important. The important point is understanding their attitude. Some of them create some classes, and some of them like the lazy create functions. When you try to get the value of the a, on line 28, it will return the getValue() function of the Lazy interface.
If we determine the type of the generic class, the T in the decompiled code will have the same type. If not, the T type will be Object.
Variance in Kotlin is Kotlin syntax for compile time. So, when you decompile the code, you can see the above code.
If you find this article helpful, let me feel your positive energies. Also, if you have any questions, you know how you can find me. I’m everywhere. :)