同时导入 class 和 class 的扩展函数
Import class and extension functions for the class simultaneously
当你写一个class(这里将是一个简单的Integer
class,所以很容易理解)并且你正在重载运算符,我已经有了关于如何为陌生人重载运算符 class 的问题,它将您的对象作为参数。看这个例子:
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()
}
}
我只是重载了简单的运算符,所以也许其他程序员可以使用这些重载来避免自己创建函数。现在我遇到了以下问题:当为你不拥有的 classes 重载运算符时,你可以像这样创建简单的扩展函数:
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
class 时,我应该把这些扩展函数放在哪里才能自动导入?
// 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.*
解决此问题,但随后包中的每个 class 都会被导入,即使它们未被使用。那么如何正确执行此操作?
除非您想将这些扩展函数放入它们自己的包中并在该包上使用 * import,否则我看不出您可以如何做得更好。您只需要一个接一个地导入扩展函数,这就是编译器知道它们来自哪里的方式。否则,您可能会在整个项目的多个包和文件中定义相同的扩展函数,并且无法在它们之间进行选择。
当你写一个class(这里将是一个简单的Integer
class,所以很容易理解)并且你正在重载运算符,我已经有了关于如何为陌生人重载运算符 class 的问题,它将您的对象作为参数。看这个例子:
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()
}
}
我只是重载了简单的运算符,所以也许其他程序员可以使用这些重载来避免自己创建函数。现在我遇到了以下问题:当为你不拥有的 classes 重载运算符时,你可以像这样创建简单的扩展函数:
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
class 时,我应该把这些扩展函数放在哪里才能自动导入?
// 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.*
解决此问题,但随后包中的每个 class 都会被导入,即使它们未被使用。那么如何正确执行此操作?
除非您想将这些扩展函数放入它们自己的包中并在该包上使用 * import,否则我看不出您可以如何做得更好。您只需要一个接一个地导入扩展函数,这就是编译器知道它们来自哪里的方式。否则,您可能会在整个项目的多个包和文件中定义相同的扩展函数,并且无法在它们之间进行选择。