kotlin - 私有(private)顶级扩展函数和类内私有(private)扩展函数的区别

标签 kotlin extension-methods member toplevel extension-function

我们目前正在将项目切换到 Kotlin,并遇到以下问题:

我们仅在给定类中需要某个扩展函数。因此,我们有两种可能性: (1) 声明扩展函数private在文件顶层或 (2) 声明扩展函数 private在类(class)内部。

关注 MCVE :

顶级示例(文件 C1.kt ):

private fun String.double() = this.repeat(2)
class C1 {
    init {
        println("init".double())
    }
}

内部类示例(文件 C2.kt ):

class C2 {
    private fun String.double() = this.repeat(2)
    init {
        println("init".double())
    }
}

问题:

  1. 除了 C1.kt 中的方法之外,这两种方法有什么区别吗?扩展功能String.double()对于其他可能的文件成员(例如同一文件中的其他类)也可见吗?

  2. 由于我们希望实现“尽可能 kotlinic”的代码,因此我们想知道这两种方法中的哪一种是建议的方法。对于上面的例子有官方的建议/风格指南吗?我认为声明扩展函数尽可能接近其预期用途被认为是一种很好的做法,因此在上面的示例中 C2 的结构会建议吗?

最佳答案

  1. Is there any difference to those two approaches, except that in C1.kt the extension function String.double() would also be visible to other possible file members (such as further classes in the same file)?

有一个区别:在类内指定扩展函数时(在示例中 C2),您还可以使用 qualified this 访问此类的实例。语法(在您的示例中 this@C2)。

  1. Since we want to achieve code "as kotlinic as possible", we would like to know which of the two approaches is the suggested one. Is there an official suggestion / style guide on the example above? I think it is considered good practice to declare extension functions as close as possible to its intended use, thus in the above example the structure of C2 would be suggested?

这是个好问题。就我个人而言,我会将扩展函数放在类之外,因为它们(通常)指定与扩展类型相关的行为,而不是与使用它们的类的类型相关的行为。但是,如果您确实在扩展函数中需要与类相关的信息,我会在类中指定它们。

关于kotlin - 私有(private)顶级扩展函数和类内私有(private)扩展函数的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54782787/

相关文章:

android - Kotlin:不可变类型对可变类型的内部变量的只读访问

testing - Camel 3 : How to intercept a route from `onException` using `interceptSendToEndpoint`

android - 如何以编程方式显示/隐藏 BottomAppBar?

c - 错误 : request for member 'Name' in something not a structure or union

c++ - C++ 中成员的枚举成员,或替代

java - Android Studio 3.o 不提供 android

c# - ActionResult 扩展不适用于 Page() ActionResult 方法

c# - 为什么这种扩展方法不起作用?

c# DateTime 添加不带扩展方法的属性

c++ - C++ 中结构的存储持续时间和成员初始化