同时导入类的类和扩展函数

时间:2018-04-23 19:29:13

标签: kotlin kotlin-extension

当你编写一个类(这里它将是一个简单的Integer类,因此它很容易遵循)并且你正在重载运算符,我已经遇到了如何使运算符重载的问题stranger类,它将您的对象作为参数。看看这个例子:

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()
    }
}

我只是简单地重载简单的运算符,所以也许另一个程序员可以使用这些重载来避免自己创建函数。现在我遇到了以下问题:当您为不属于您的类重载运算符时,您可以创建这样的简单扩展函数:

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)
...

但在使用Integer类时,我在哪里可以自动导入这些扩展函数?

// 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`

我可以通过import com.example.*解决此问题,但是即使它们仍然未使用,也会导入包中的每个类。那么我该怎么做呢?

1 个答案:

答案 0 :(得分:0)

除非你想将这些扩展功能放在他们自己的包中并在该包上使用* import,否则我不知道你怎么能做得更好。您只需逐个导入扩展函数,即编译器如何知道它们的来源。否则,您可以在整个项目中的多个包和文件中定义相同的扩展函数,并且无法在它们之间进行选择。