Search code examples
kotlinkotlin-extension

Import class and extension functions for the class simultaneously


When you are writing a class (here it will be a simple Integer class, so it will be easy to follow) and you are overloading operators, I already had a problem on how to overload the operator for a stranger class, which takes your object as a parameter. Look at this example:

package com.example

class Integer(var value: Int) {

    operator fun plus(x: Integer) = Integer(value + x.value)
    operator fun plus(x: Int) = Integer(value + x)
    operator fun minus(x: Integer) = Integer(value - x.value)
    operator fun minus(x: Int) =  Integer(value - x)

    override fun toString(): String {
        return value.toString()
    }
}

I simply overload simple operators so maybe another programmer can use these overloads to avoid creating functions on his own. Now I got following problem: When overloading operators for classes you don't own, you can create simple extension functions like this:

operator fun Int.plus(x: Integer) = Integer(x.value + this) // This is referencing to the actual `Int` object
operator fun Int.minus(x: Integer) = Integer(x.value - this)
...

but where do I got to place these extension functions to be imported automatically when the Integer class is being used?

// Main.kt
import com.example.Integer

fun main(args: Array<String>) {
    val int1: Integer(2) + 3 // Compiles
    val int2: 3 + Integer(2) // Doesn't compile unleast you add the extensions functions in `Integer` before the class declaration
                             // (between the package declaration and the class) and import them explicity
                             // like `import com.example.plus`

I could workaround this by import com.example.*, but then every single class in the package gets imported even if they remain unused. So how do I do this correctly?


Solution

  • Unless you want to place these extension functions into their own package and use a * import on that package, I don't see how you could make this any better. You just have to import the extension functions one by one, that's how the compiler knows where they come from. Otherwise you could have the same extension functions defined in multiple packages and files all over your project and there would be no way to choose between them.