gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:38:17 25 4
gpt4 key购买 nike

我们目前正在将项目切换到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com