Scala:单个文件中的多个对象和类或每个对象/类都有自己的文件 [英] Scala: multiple objects and classes in a single file or each object/class its own file

查看:56
本文介绍了Scala:单个文件中的多个对象和类或每个对象/类都有自己的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've recently started programming in Scala, coming from Python and Java I was wondering what the correct way or the accepted way is when defining objects/classes in Scala. Scala supports, just like python, to add several class or object definitions in a single file.

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

So purely from an accepted structure perspective, does every object need to be defined in its own file or are you allowed to choose this yourself?

推荐答案

官方有章节Scala Style指南.这本身就很清楚,但我会在这里留下一些引号.

There is a chapter in the official Scala Style Guide on this. It's pretty clear in itself, but I'll just leave some quotes here.

核心思想是:

通常,文件应该包含一个逻辑编译单元.逻辑"是指一个类、特征或对象.

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

当然,伴生对象有一个例外:

There is, of course, an exception for companion objects:

此指南的一个例外是具有伴生对象的类或特征.伴生对象应与其对应的类或特征分组在同一文件中.

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 只能在同一个文件中工作.

There is also the fact that sealed only works within the same file.

尽管如上所说,但仍有一些重要情况需要在单个文件中包含多个编译单元.一个常见的例子是一个密封特性和几个子类.由于密封超类(和特征)的性质,所有子类型必须包含在同一个文件中.

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.

大多数时候,案例类只是简单的数据容器,可以组合在一起.

Most of the time, case classes are just simple data containers and can be grouped together.

另一种情况是,多个类在逻辑上形成一个单一的、有凝聚力的组,共享概念到通过将它们包含在单个文件中来极大地维护维护的程度.

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 文件的命名约定:

Finally, there is a naming convention for exempted multi-unit Scala files:

所有多单元文件都应以驼峰命名,首字母小写.

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

因此:将您的 Scala 类和对象放在单独的文件中,除非它们属于上述三个例外之一.

So: put your Scala classes and objects in separate files, unless they fall into one of the three mentioned exceptions.

这篇关于Scala:单个文件中的多个对象和类或每个对象/类都有自己的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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