Kotlin 中的包保护替代方案 [英] Package protected alternative in Kotlin

查看:24
本文介绍了Kotlin 中的包保护替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,我们为类提供了包保护(默认)修饰符,它允许我们在一个包中拥有多个类,但只公开少数几个并保持逻辑封装.

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,情况似乎并非如此.如果我希望几个类彼此可见,但不能再进一步,我必须使用私有修饰符来限制对单个文件的可见性.

With Kotlin this doesn't seem to be the case. If I want a few classes to be visible to each other but no further, I have to use a private modifier which limits visibility to a single file.

因此,如果您希望在一个包中有 10 个类,但其中只有一个是公开的,则您必须拥有一个包含所有类的大文件(并且到处都是 private).

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 中实现一些类似的模块化?

Is this normal practice or there is a way to achieve some similar modularity in Kotlin?

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

I don't understand: if they have the notion of a package, why did they get rid of package protected access?

更新:毕竟我们可能有包保护的可见性
在这里查看讨论

更新:如果您通读讨论后仍然认为这是该语言的必备功能,请投票 这里

推荐答案

Kotlin 与 Java 相比,似乎对包模型的依赖程度较低(例如,目录结构与包无关).相反,Kotlin 提供内部可见性,专为模块化项目架构而设计.使用它,您可以将部分代码封装在单独的模块中.

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.

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

So, on top level declarations you can use

  • private 限制对文件的可见性
  • internal 限制模块的可见性
  • 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 中的包保护替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆