I am pretty new to Kotlin, I am looking at the null safety and Elvis operators and would like to know more on how these are implemented to work on top of JVM.
Operators I am interested to know the implementation of:
? ?. ?:
But I am unable to locate any source associated with these. Are the implementations hidden? From my IDE also I cannot locate any source related to these, magic?

From the Kotlinlang.org: It specifies that Kotlin is an open source language: Kotlin is an open-source statically typed programming language that targets the JVM, Android, JavaScript and Native
Note: I know I don't need to specify null on the right hand side of the Elvis, this is just to send my point across in the screen grab.
Disclaimer: I'm no expert on the Kotlin compiler. I just looked at the source code.
The tokens are defined here:
KtSingleValueToken SAFE_ACCESS = new KtSingleValueToken("SAFE_ACCESS", "?.");
KtSingleValueToken ELVIS = new KtSingleValueToken("ELVIS", "?:");
KtSingleValueToken QUEST = new KtSingleValueToken("QUEST", "?");
These tokens are parsed by the Kotlin compiler itself, they are not defined in Java. This is why you cannot jump to a definition - they are re-written by the compiler.
I don't know how they are implemented, but checking out the Kotlin source and using the above tokens as a starting point might be useful.
Those features are "embedded" into the language. So you can't really dig into the code at compile time. An equivalent example to this would be trying to get the implementation of a while loop or a when statement. Those are language features that just generate compiled code
One thing that you could do if you're curious would be to decompile a simple program using them and check the result. However, as the generated bytecode may include some optimizations, the result might differ between different use cases.
The most important thing you need to know is what they do and how to use them. You can find an example of equivalent behaviour between null safe operators and java code in the Kotlin Koans, in which this Java code
public void sendMessageToClient(
@Nullable Client client,
@Nullable String message,
@NotNull Mailer mailer
) {
if (client == null || message == null) return;
PersonalInfo personalInfo = client.getPersonalInfo();
if (personalInfo == null) return;
String email = personalInfo.getEmail();
if (email == null) return;
mailer.sendMessage(email, message);
}
can be rewritten in Kotlin as
val email = client?.personalInfo?.email
if (email != null && message != null) {
mailer.sendMessage(email, message)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With