gpt4 book ai didi

同一文件中的Scala特征和类

转载 作者:行者123 更新时间:2023-12-04 16:49:50 24 4
gpt4 key购买 nike

将特性和实现它的类放在 Scala 的同一个文件中是一个好习惯吗?
例如。在 B.scala 你有:

trait A
class B extends A

最佳答案

你可以,但如果他们不是密切相关的,你最好不要。
实用的原因是向文件添加许多类/特征可能会使编译(尤其是增量编译)变慢。
这是来自 https://virtuslab.com/blog/zinc-sbt-friendly-code/#less-is-more 的摘录

Less classes/traits/objects per source file means more time saved. Scalac can compile nothing less than a whole source. Even if Zinc knows that only a one-line object needs to be recompiled, it still has to compile the whole source (and all implicits macros and other nasty stuff inside).

The solution is as simple as possible: split your sources! If incremental compilation is not enough to convince you, you should be aware that it should also help with compilation time or even result in less conflicts during merges.


值得注意的异常(exception)是:
  • sealed trait 的家庭:sealed允许扩展 trait仅在源文件中,因此在这种情况下,您必须保留所有扩展该 trait 的类。一起。
  • 类和伴随对象:一个 object仅当在同一个源文件中定义一个类时,才将其命名为它的伴生对象,因此您必须再次将它们放在一起。

  • official style guide似乎证实了这种方法,即使它没有明确提到编译性能:

    As a rule, files should contain a single logical compilation unit. By “logical” I mean a class, trait or object. 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.

    关于同一文件中的Scala特征和类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45956134/

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