是否可以使用Kotlin中的命名空间对扩展进行分组?

是否可以使用Kotlin中的命名空间对扩展进行分组?,kotlin,Kotlin,添加太多的扩展很快就会变得杂乱无章,因此将扩展分组到框架名称空间下将是理想的选择。 例如,不要将所有函数直接添加到Int,如: fun Int.operationA() { println("A $this") } fun Int.operationB() { println("B $this") } // and use it like: 123.operationA() 123.operationB() 我更愿意在框架名称空间中使用它,如: 123.framewor

添加太多的扩展很快就会变得杂乱无章,因此将扩展分组到框架名称空间下将是理想的选择。 例如,不要将所有函数直接添加到Int,如:

fun Int.operationA() { 
    println("A $this")
}

fun Int.operationB() { 
    println("B $this")
}

// and use it like:
123.operationA()
123.operationB()
我更愿意在框架名称空间中使用它,如:

123.framework.operationA()
123.framework.operationB()

// Declaring it like this would be nice
fun Int.framework.operationA() { 
    println("A $this")
}
在Swift中,可以使用带有默认实现的协议和扩展来实现这一点。 在科特林怎么样?有什么办法吗

class IntFramework(val x: Int) {
    fun operationA() ...
    fun operationB() ...
}

// or
class IntFramework(val x: Int)
fun IntFramework.operationA() ...
fun IntFramework.operationB() ...

val Int.framework get() = IntFramework(this)
如果您想添加更多的方法,请在
IntFramework
中将它们声明为扩展。但这不是惯用的,可能会让其他使用或依赖于您的代码的开发人员感到惊讶(可能不是来自Swift?)


如果您只需要支持Kotlin 1.3+,那么您可以使用它,与直接在
Int
上定义扩展方法相比,它应该可以消除任何开销。

使用包不会达到您想要的效果吗?您可以在此处使IntFramework类
内联
,以至少降低开销成本(从Kotlin 1.3开始,此功能仍处于试验阶段)。工作完美,谢谢!实现可能看起来有点奇怪,但没有人需要知道它是如何在内部实现的,每个人只需要记住使用。框架…实际上,要在Swift中实现这一点,会让人更加困惑