Search code examples
kotlinkotlin-extension

Kotlin Class Extension


I'm just learning Kotlin as a fun side-project for Project Euler. I just started literally 5 minutes ago, in IntelliJ IDEA.

I have this code:

fun Number.isMultipleOf(n: Number): Boolean {
    return this % n == 0
}

fun main(args: Array<String>){
    println(10.isMultipleOf(5))
}

The compile error is this:

Kotlin: Unresolved reference.  None of the following candidates is applicable because of receiver type mismatch:
@Deprecated @InlineOnly public inline operator fun BigDecimal.mod(other: BigDecimal): BigDecimal defined in kotlin

I'm experienced in Java, Python, C++ and Swift so I figured Kotlin shouldn't be that much of a challenge. But WTF is a "receiver type"?

How can I fix this compile error while getting the desired functionality out of the Number class extension?


Solution

  • Just trying to explain the term receiver type and the error mentioned.

    Error occurs in the line

    return this % n == 0
    

    If you look closely, this is of variable type Number. so Number is your receiver type in the statement above(as it receives second operand to operate). Number is the abstract super class for all Numeric objects like Int, Float ... in Kotlin, which does not have inline function to perform modulo(%) operation. Hence you are getting the error. Hope this helps.