gpt4 book ai didi

Scala:单个文件中的多个对象和类或每个对象/类都有自己的文件

转载 作者:行者123 更新时间:2023-12-03 08:36:14 26 4
gpt4 key购买 nike

我最近开始在 Scala 中编程,来自 Python 和 Java 我想知道在 Scala 中定义对象/类时正确的方法或公认的方法是什么。 Scala 支持,就像 Python 一样,在单个文件中添加多个类或对象定义。

因此,纯粹从公认的结构角度来看,是否每个对象都需要在自己的文件中定义,还是允许您自己选择?

最佳答案

官方有章Scala Style Guide在这一点上。这本身就很清楚,但我会在这里留下一些引述。

核心思想是:

As a rule, files should contain a single logical compilation unit. By “logical” I mean a class, trait or object.



当然,伴生对象有一个异常(exception):

One exception to this guideline is for classes or traits which have companion objects. Companion objects should be grouped with their corresponding class or trait in the same file.



还有一个事实是 sealed只能在同一个文件中工作。

Despite what was said above, there are some important situations which warrant the inclusion of multiple compilation units within a single file. One common example is that of a sealed trait and several sub-classes. Because of the nature of sealed superclasses (and traits), all subtypes must be included in the same file.



大多数情况下,案例类只是简单的数据容器,可以组合在一起。

Another case is when multiple classes logically form a single, cohesive group, sharing concepts to the point where maintenance is greatly served by containing them within a single file.



最后,豁免的多单元 Scala 文件有一个命名约定:

All multi-unit files should be given camelCase names with a lower-case first letter.



所以:将您的 Scala 类和对象放在单独的文件中,除非它们属于上述三个异常(exception)之一。

关于Scala:单个文件中的多个对象和类或每个对象/类都有自己的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24365548/

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