At which situations does implicit conversion happen?

I am a beginner in Kotlin.
I’m most familiar with Python, and I just read through the basic Java Tutorial before jumping into Kotlin.

A question came up in my mind while reading this section of the documentation of Kotlin

What I have understood from above section of the documentation is:

  • For assignments =, implicit type conversion happens. If the lefthand side’s type is a supertype or same type of righthand side’s type the code would compile. Otherwise it’s a compile error. In case of Int and Long, they are both subtypes of Number but neither of them subtypes of each other, so the implicit conversion would not work. Therefore we need to use methods like .toLong() or .toInt() to explicitly convert them.
    indent preformatted text by 4 spaces
    Then when I read the part
val l = 1L + 3 // Long + Int => Long

I started wondering if implicit type conversion would be taking place in this situation.

The documentation says this has to do with the operator overloading.
How is this operator overloading implemented under the hood?
I tried to find the source code at Github ,
but here the functions are only declared but not implemented. Where can I find the implementations?

It seems that operation overloading does not actually perform type conversion. Do we just implementing all possible functions with same name but different parameter type signatures, so that the type is inferred, then the function with the matching signature is selected?

And the general question: In Kotlin, exactly at which situations does implicit conversion happen?

No, it doesn’t. Kotlin doesn’t have implicit type conversion. There is one exception with number literals.
So val foo: Long = 1 is ok even though 1 as a literal generally is of type Int.

This is indeed done by operator overloading. The reason you can’t find the implementations is that they are directly translated into the specific jvm bytecode instructions. I don’t know the compiler well enough to point to a specific file (if this is even possible).

Yes. The standard library contains a plus method for each combination of Number types. If you were to add a new class extending Number you would need to provide your own implementations of those functions or you couldn’t use mathmatical operators.

Thanks for the reply.

So you’re saying that except for the number literals, there’s no such thing as implicit type conversion in Kotlin. That clarified my confusion. :slight_smile: