Search code examples
scalacompilationkotlinimplicitkotlin-extension

How do Kotlin's extension functions work?


Let's say I want an integer that supplies a square method.

Kotlin:

fun Int.square() = this * this

usage:

println("${20.square()}")

doc:

Extensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type.

We would like to emphasize that extension functions are dispatched statically

My expectation would've been that they simply add it to the member functions of the extended class during compilation, but that is what they explicitly deny, so my next thought was it could be "sort of" like scala implicits.

Scala:

object IntExtensions{
    implicit Class SquareableInt(i:Int){
        def square = i*i
    }
}

usage:

import IntExtensions._

and then

println(f"${20.square}")

doc:

An implicit class is desugared into a class and implicit method pairing, where the implciit method mimics the constructor of the class.

The generated implicit method will have the same name as the implicit class.

But scala implicits create a new class, that would disable the usage of this.

So ... how IS it that Kotlin extends classes? "Make callable" isn't telling me much.


Solution

  • In your case Kotlin just create simple utils-class with name "filename"Kt and static method "int square(int x)" (java pseudo-code)

    From Java it look something like this

    // filename int-utils.kt
    final class IntUtilsKt {
        public static int square(int x) {
            return x * x;
        }
    }
    

    And after this all calls to

    val result = 20.square()

    will be transformed (on byte-code level) to

    val result = IntUtilsKt.square(20);

    P.S. You can see it yourself using IDEA action "Show Kotlin byte-code"