Kotlin.any or kotlin.any? which is equivalent java.lang.object


hi everyone
Has my mind got a question?
kotlin,any or kotlin.any? which is equivalent java.lang.object
Will be convert kotlin.any or kotlin,any? into java.lang.object after compile?


Short answer: both

Long answer:
Java itself has no concept of nullable or not null like kotlin. Therefor there is no way to represent nullability in java directly. Kotlin does however use the @Nullable and @NotNull annotation to save this data, and kotlin writes nullability into the @Metadata annotation.
So back to your question. I think the easiest way is to look at the places where kotlin and java interact. Lets say we have the following kotlin functions:

fun foo1(a: Any) ...
fun foo2(a: Any?) ...
fun foo3(): Any ...
fun foo4(): Any? ...

In java they would look like this

void foo1(@NotNull Object a) ...
void foo2(@Nullable Object a) ...
@NotNull Object foo3() ...
@Nullable Object foo4() ...

This does not mean that java code can not do this

foo1(null)    // no compile error here

The java compiler does not care about those annotations. But IDEs such as Intellij Idea or Eclipse should at least warn you about this. Also the kotlin compiler knows that java might call foo1 with null and adds a null- check for each parameter automatically.
Now there is one more important interaction between kotlin and java. Let’s take at the following java function.

Object soemJavaFunction() ...

When calling this function from kotlin, the result of this function is neither Any nor Any? it is Any!. This means it is a platform type, which can be either nullable or not. Basically you decide whether it is nullable or not. You do this simply by either using it directly or doing null checks.
So Any, Any? and Any! are all 3 equivalent to java.lang.Object. They only differ in the way kotlin let’s you use them.

If you want more information I’d look at


thank you so much. so Any , Any? , Any! are collectively equivalent , right?


What do you mean by collectively?

Again yes and no. In kotlin they represent 3 different concepts (Nullable type, NotNull type and a platform type). So they are not the same. They only look the same from a java perspective.


So each of them separate, are they the equivalent?


In terms of low-level JVM bytecode, they are equivalent. On the higher-level Kotlin language, they are different.


i got it:sweat_smile:
from you and Wasabi375 thanks


Keep also in mind that the JVM is only one of several target platforms. There might exist a platform now or in future, where there is indeed a low level support for nullable types.

Just because there is no support on JVM does not mean it is an inherent property of low level kotlin representation.