【问题标题】:Import class and extension functions for the class simultaneously同时导入类的类和扩展函数
【发布时间】:2018-04-23 19:29:13
【问题描述】:

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

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.* 解决这个问题,但是包中的每个类都会被导入,即使它们仍未使用。那么我该如何正确地做到这一点呢?

【问题讨论】:

    标签: kotlin kotlin-extension


    【解决方案1】:

    除非您想将这些扩展函数放入它们自己的包中并在该包上使用 * 导入,否则我看不出如何使这变得更好。您只需要一个一个地导入扩展函数,这就是编译器知道它们来自哪里的方式。否则,您可能会在整个项目的多个包和文件中定义相同的扩展函数,并且无法在它们之间进行选择。

    【讨论】:

    • 我可以问一下,当您不拥有位于左侧的对象时,为什么 Kotlin 开发人员没有实现一种简单的方法来覆盖运算符?是否有特殊的原因或限制导致开发者陷入困境?
    • 基本上他们希望非常清楚函数的来源。如果您使用 IntelliJ,它会在大部分时间为您处理好。但听起来您正在寻找类似于 Groovy 中的 MetaProgramming 的东西,它可以动态地确定应该发生什么。这不是 Kotlin 的意义所在……
    猜你喜欢
    • 1970-01-01
    • 2016-11-28
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 2011-07-28
    • 1970-01-01
    • 2014-03-22
    相关资源
    最近更新 更多