Scala trait 和 class 在同一个文件中
Scala trait and class in the same file
将特征和 class 在 Scala 中的同一个文件中实现它是一个好习惯吗?
例如。在 B.scala 你有:
trait A
class B extends A
是的,您可以 class 在同一个 scala 文件中扩展特征。另外,查看 sealed trait
看看它是否与您相关。
你可以,但如果它们不是密切相关,你最好不要。
务实的原因是在文件中添加很多classes/traits可能会使编译(尤其是增量编译)变慢。
这是来自 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.
值得注意的例外是:
sealed trait
家族:sealed
允许仅在源文件中扩展 trait
,因此在这种情况下,您必须保留所有 classes 一起扩展 trait
。
classes 和伴生对象:以 class 命名的 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.
将特征和 class 在 Scala 中的同一个文件中实现它是一个好习惯吗? 例如。在 B.scala 你有:
trait A
class B extends A
是的,您可以 class 在同一个 scala 文件中扩展特征。另外,查看 sealed trait
看看它是否与您相关。
你可以,但如果它们不是密切相关,你最好不要。
务实的原因是在文件中添加很多classes/traits可能会使编译(尤其是增量编译)变慢。
这是来自 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.
值得注意的例外是:
sealed trait
家族:sealed
允许仅在源文件中扩展trait
,因此在这种情况下,您必须保留所有 classes 一起扩展trait
。classes 和伴生对象:以 class 命名的
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.