Scala 中符号文字的一些示例用例是什么? [英] What are some example use cases for symbol literals in Scala?

查看:33
本文介绍了Scala 中符号文字的一些示例用例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我在 Scala 上读到的内容来看,符号文字的使用并不是很清楚.有人愿意分享一些现实世界的用途吗?

The use of symbol literals is not immediately clear from what I've read up on Scala. Would anyone care to share some real world uses?

符号文字是否涵盖了特定的 Java 习语?哪些语言有类似的结构?我来自 Python 背景,不确定该语言中是否有类似的东西.

Is there a particular Java idiom being covered by symbol literals? What languages have similar constructs? I'm coming from a Python background and not sure there's anything analogous in that language.

是什么促使我使用HelloWorld 与HelloWorld"?

What would motivate me to use 'HelloWorld vs "HelloWorld"?

谢谢

推荐答案

在 Java 术语中,符号是内部字符串.这意味着,例如,引用相等比较(Scala 中的 eq 和 Java 中的 ==)给出与正常相等比较(==)相同的结果code> 在 Scala 中和 equals 在 Java 中):'abcd eq 'abcd 将返回 true,而 "abcd" eq "abcd" 可能不会,取决于 JVM 的奇思妙想(嗯,它应该用于文字,但不适用于一般动态创建的字符串).

In Java terms, symbols are interned strings. This means, for example, that reference equality comparison (eq in Scala and == in Java) gives the same result as normal equality comparison (== in Scala and equals in Java): 'abcd eq 'abcd will return true, while "abcd" eq "abcd" might not, depending on JVM's whims (well, it should for literals, but not for strings created dynamically in general).

其他使用符号的语言有 Lisp(使用 'abcd,如 Scala)、Ruby(:abcd)、Erlang 和 Prolog(abcd>;它们被称为原子而不是符号).

Other languages which use symbols are Lisp (which uses 'abcd like Scala), Ruby (:abcd), Erlang and Prolog (abcd; they are called atoms instead of symbols).

当我不关心字符串的结构时,我会使用符号并将其纯粹用作某物的名称.例如,如果我有一个表示 CD 的数据库表,其中包含一个名为price"的列,我不在乎price"中的第二个字符是r",或者关于连接列名;因此 Scala 中的数据库库可以合理地为表名和列名使用符号.

I would use a symbol when I don't care about the structure of a string and use it purely as a name for something. For example, if I have a database table representing CDs, which includes a column named "price", I don't care that the second character in "price" is "r", or about concatenating column names; so a database library in Scala could reasonably use symbols for table and column names.

这篇关于Scala 中符号文字的一些示例用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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