How to add a KDoc comment for the receiver of a Kotlin extension function (first parameter in Java, `this` in Kotlin)

Tags: , , ,



Consider this non-extension function:

fun checkArguments(expression: Boolean) {
    if (!expression) {
        throw IllegalArgumentException()
    }
}

When I use this function in kotlin and java, I can see its parameter name: expression.

I could also write this same functionality as an extension function:

fun Boolean.checkArguments() {
    if (!this) {
        throw IllegalArgumentException()
    }
}

When I write it as an extension function in this manner, the parameter name of the Boolean that it is called on (the this variable within the function, AKA the receiver) shows up as $this$checkArguments. How can I add a KDoc documentation comment for this parameter? Using @param $this$checkArguments doesn’t seem to document it.

Answer

You can use @receiver to document the receiver of the extension function. Here is the relevant documentation.

For example:

/**
 * @receiver A String that is at least four characters long
 */
fun String.firstFour() = this.substring(0, 4)


Source: stackoverflow