[英]The practical use of productPrefix def in Product.scala trait
Maybe silly question, but I can't find any useful explanation about this.也许是愚蠢的问题,但我找不到任何有用的解释。 I've read the documentation, but I'm confused, maybe one use is to compare types, at some extent.
我已经阅读了文档,但我很困惑,也许一种用途是在某种程度上比较类型。 Any idea or practical example?
有什么想法或实际例子吗?
Blockquote
块引用
A string used in the toString methods of derived classes.
派生类的 toString 方法中使用的字符串。 Implementations may override this method to prepend a string prefix to the result of toString methods.
实现可以覆盖此方法以在 toString 方法的结果前添加字符串前缀。 Returns: in the default implementation, the empty string Blockquote
返回:在默认实现中,空字符串 Blockquote
Tuples (which extend Product
) are printed like this:元组(扩展
Product
)打印如下:
(x1, ..., xN)
^ opening parenthesis
^ elements
^ commas
^ closing parenthesis
Case classes (which also extend Product
) are printed like this:案例类(也扩展
Product
)打印如下:
CaseClassName(x1, ..., xN)
^^^^^^^^^^^^^ class name
^ opening parenthesis
^ elements
^ commas
^ closing parenthesis
Since both inherit from Product
, it's possible to provide a default toString
implementation once in the Product
-trait, which produces something like:由于两者都继承自
Product
,因此可以在Product
-trait 中提供一次默认的toString
实现,这会产生如下内容:
${productPrefix}(x1, ..., xN) // ascii-art, not actual code
with productPrefix = ""
in the case of tuples and productPrefix = "CaseClassName"
for case classes. productPrefix = ""
在元组的情况下和productPrefix = "CaseClassName"
对于案例类。
Given that Tuple
s are such an integral part of the language, I could imagine that using the inheritance of a method implementation from the Product
trait could have served an actual purpose of "dogfooding" in the earliest phases of the compiler development: this might actually be one of the first and one of the simplest uses of trait
s.鉴于
Tuple
是该语言不可或缺的一部分,我可以想象使用Product
trait 的方法实现的 inheritance 可以在编译器开发的最早阶段达到“dogfooding”的实际目的:这实际上可能是trait
的第一个也是最简单的用法之一。 (It seems somewhat plausible to me, but it's purely speculative; I did not attempt to dig into the commit history.) (这对我来说似乎有些合理,但这纯粹是推测性的;我并没有试图深入研究提交历史。)
Otherwise, there is no deeper meaning in it.否则,就没有更深层次的意义。 It's just a part of the
toString
implementation.它只是
toString
实现的一部分。 You should never rely on the toString
implementation for anything, and you should never use it for any kind of program logic.您永远不应该依赖
toString
实现来做任何事情,也不应该将它用于任何类型的程序逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.