Suppose I have some Utils.kt file which will contain only some utility functions, no classes, no objects. And suppose that those functions use some common set of constant values.

所以我做了这样的事情:

package myapp

private val CONST1 = 1
private val CONST2 = 2

public fun function1() {}
public fun function2() {}

Unfortunately Kotlin treats private as "available to the whole package". So CONST1 and CONST2 are available to all files which are in the same package. The only way to isolate them is to move this file to a separate package.

但是,如果我有几个类似这样的实用程序文件,每个文件都有自己的private个常量集,会怎么样呢?那么我只有两个 Select :将它们中的每一个都移动到一个唯一的包中,或者放弃,让它们的const可以在任何地方访问.

Either way seems to create clutter.

有什么 Select 或建议吗?

(实际上,我必须说这是我在Kotlin中为数不多的困扰我的事情之一--没有办法使某个实体是文件本地的(不使用一些语法技巧):它要么对整个包可用,要么对所有人都可用.)

UPD:这个问题现在已经过时了(见公认的答案)

推荐答案

Top-level declarations with private visibility are visible only in the file where they are declared.

(original answer, valid when the question was asked: Kotlin does not have any concept of file-local scope, and to the best of my knowledge there are no plans to introduce it. If you don't like package scope (why?), you can create an object encapsulating the functions and the private constants that they use.

Kotlin相关问答推荐

在没有外部 map 的情况下转换列表项

Kotlin -从列表中获取特定过滤器的唯一列表值

我如何测试一个可组合组件没有显示,但如果它不存在也接受?

插入/更新/upsert时不发出房间流

可选的.在kotlin中不使用泛型参数

Kotlin:将泛型添加到列表任何>

jOOQ Kotlin Coroutines - Select all and exists查询

房间数据库操作中的协程取消

为什么使用 return instance ?: synchronized(this) { instance ?: PreferenceParameterState(context) } 时无法获得单例?

限制通用Kotlin枚举为特定类型

Kotlin 基于参数类型的返回类型推断

为什么 Kotlin main 函数需要 @JVMStatic 注解?

使用事务时未调用 Kafka ConsumerInterceptor onCommit

Kotlin 数据类中的大量参数

Kotlin 编译器在构造函数中报告未使用的表达式,以便构建器采用 vararg lambda

类型是什么意

项目未与 Gradle 链接

未解决的参考 dagger 2 + kotlin + android gradle

从 java 活动 *.java 启动 kotlin 活动 *.kt?

如何将 Kotlin 的 `with` 表达式用于可空类型