How kotlin implements that Kotlin use operator overloaded from Java?

Hi,

In document,

Kotlin allows using any Java methods with the right name and signature as operator overloads
Calling Java from Kotlin | Kotlin Documentation

I want to know how kotlin implements.

When Kotlin use operator overloaded from java, how to work in background? compiler?
In debug, there is no evidence in stacktrace between kotlin with java.

What is the part of the implementation that concerns you? Operators are basically a syntactic sugar, they are compiled to regular function calls. Whenever you write list[i] in Kotlin, it is actually compiled to list.get(i), so there is no reason we can’t do the same for Java class.

I’m just curious how to compile working with that syntactic sugar.

In IntelliJ, you can go into Tools › Kotlin › Show Bytecode, then select your Kotlin file, then press Decompile. This will show you the (approximate) Java code created by the Kotlin compiler.

Then, you can write any Kotlin code you want and see how it looks like.

1 Like

I think it’s pretty obvious. The compiler sees list[i]. It checks what type list has. If it’s a Kotlin type that provides an explicit operator fun get, it uses just that. If not, it checks whether it’s a Java array. If so, does the same thing that Java would do. If not, it checks whether it’s a Java class that has a get method (no operator needed here because Java has no operators). If so, than that [i] is compiled into get(i). If not, it checks whether there’s an extension method…

This could be partly wrong or incomplete, but roughly it must be something like this.

Pretty much the same way object.value = ... is compiled into object.setValue(...).