In Java, we have the package protected (default) modifier for classes, which allows us to have many classes in a single package but exposes only a few and keeps the logic encapsulated.

对于Kotlin 来说,情况似乎并非如此.如果我想让几个类彼此可见,但不能再进一步,我必须使用私有修饰符来限制单个文件的可见性.

So if you want 10 classes in a package but only one of them to be public, you'd have to have one huge file with all the classes in it (and private all over the place).

这是正常的做法还是有办法在Kotlin中实现类似的模块化?

我不明白:如果他们有包的概念,为什么他们要取消包保护访问呢?

Update: We might have package protected visibility after all
see the discussion here

Update: If you read through the discussion and still think this is a must-have feature for the language, please vote here

推荐答案

Kotlin, compared to Java, seems to rely on packages model to a lesser degree (e.g. directories structure is not bound to packages). Instead, Kotlin offers internal visibility, which is designed for modular project architecture. Using it, you can encapsulate a part of your code inside a separate module.

因此,在顶级声明中,您可以使用

  • private to restrict visibility to the file
  • internal to restrict visibility to the module

At this point, there is no other option for visibility restriction.

Kotlin相关问答推荐

Ktor错误:未指定端口或sslPort

如何创建继承抽象的匿名对象的新实例?

在Webflux应用程序中通过kotlin协程启动fire and forget job

为什么";";.equals(1)在柯特林语中是有效的,但";";=1是无效的?

在Jetpack Compose中创建波浪式文本动画:顺序中断问题

在 Kotlin 中将 Array 转换为 IntArray 时丢失值

kotlin短路列表判断吗?

为什么会出现Kotlin.Unit错误以及如何修复它?

这是什么 Kotlin 类型:(String..String?)

Kotlin:不允许在辅助构造函数参数上使用val

Kotlin - 当表达式返回函数类型

Kotlin Compose,在行中对齐元素

Kotlin get字段注释始终为空

在Kotlin中传递并使用函数作为构造函数参数

未找到导入 kotlinx.coroutines.flow.*

Kotlin/JS,Gradle 插件:无法加载@webpack-cli/serve命令

Spring Boot:更改属性占位符符号

Kotlin:如何修改成对的值?

任何处理器都无法识别以下选项:'[kapt.kotlin.generated, room.incremental]'

如何在 IntelliJ IDEA 中禁用粘贴时将 Java 转换为 Kotlin?