Search code examples
kotlinreceivercompanion-object

Kotlin - Companion Object with Receiver Function


I guess it's an outright "NO", but here is my class

class KotlinReceiverFunction {

    val multiplyBy = fun Int.(value: Int) = this*value

    companion object {
        fun printMultiplicationResult(a: Int, b: Int) = a.multiplyBy(b) // error
    }
}

My question - is Receiver Function only allowed within a specific scope i.e. same as Lambdas? Or, can I get to work somehow in a companion object?

Regards


Solution

  • There are no restrictions on where a function with a receiver could be used. The problem in your case is different: multiplyBy is an instance member, so you need an instance of KotlinReceiverFunction to use it. It would be exactly the same if this function would not use a receiver:

    val multiplyBy = fun (value1: Int, value2: Int) = value1*value2
    
    companion object {
        fun printMultiplicationResult(a: Int, b: Int) = multiplyBy(a, b) // error
    }
    

    To fix the problem you need to initialize an instance of KotlinReceiverFunction:

    fun printMultiplicationResult(a: Int, b: Int) =
        with(KotlinReceiverFunction()) { a.multiplyBy(b) } // works
    

    Although, I think this is not exactly what you need.