在 Scala 中使用符号的实际例子? [英] Practical examples of using symbols in Scala?

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

问题描述

Scala 有符号 - 名称以单引号 ' 开头,是一种字符串常量.

我知道 Ruby 中的符号(它们以冒号开头).在 Ruby 中,它们用于一些元编程任务,例如为成员变量生成 getter 和 setter(例如 attr_reader :namename 生成 getter).

我还没有在 Scala 代码中看到大量使用符号.Scala 中符号的实际用途是什么?

解决方案

符号真的适合 Scala 吗?

在 Lisp 的奇妙世界中,代码被表示为表示自身(字符串、数字等)的文字对象的嵌套列表,以及用作类、函数和变量等事物的标识符的符号.由于 Lisp 代码具有非常简单的结构,Lisp 允许程序员操作它(在编译时和运行时).显然,在这样做时,程序员不可避免地会遇到作为数据对象的符号.

所以符号在任何情况下都是(并且必须是)Lisp 中的对象,那么为什么不将它们用作哈希表键或枚举呢?这是做事的自然方式,它使语言保持简单,因为您不必定义特殊的枚举类型.

总而言之,符号自然用于代码操作、枚举和键控.但是默认情况下,Java 人员不使用身份作为哈希键之间的等价关系(传统 Lisp 会这样做),因此他们可以只使用字符串作为键.枚举类型在 Scala 中单独定义.最后,该语言根本不支持代码即数据.

所以不,我的印象是符号不属于 Scala 语言.也就是说,我将密切关注对这个问题的答复.他们可能仍然在 Scala 中展示了我现在无法想到的符号的真正使用.

(附录:根据 Lisp 方言,Lisp 符号也可能是命名空间限定的,这当然是操作代码时非常有用的功能,而字符串则没有有.)

Scala has symbols - names that start with a single quote ' and which are a kind of string constants.

I know symbols from Ruby (where they start with a colon). In Ruby they are used for some meta-programming tasks, like generating getters and setters for member variables (for example attr_reader :name to generate a getter for name).

I haven't seen a lot of use of symbols in Scala code yet. What are practical uses for symbols in Scala?

解决方案

Do symbols really fit into Scala?

In the wonderful land of Lisp, code is represented as nested lists of literal objects that denote themselves (strings, numbers, and so on), and symbols, which are used as identifiers for things like classes, functions, and variables. As Lisp code has a very simple structure, Lisp allows the programmer to manipulate it (both at compile-time and run-time). Clearly, when doing this, the programmer will inevitably encounter symbols as data objects.

So symbols are (and need to be) objects in Lisp in any case, so why not use them as hash table keys or as enums as well? It's the natural way of doing things, and it keeps the language simple, as you don't have to define a special enumeration type.

To summarise, symbols are naturally used for code manipulation, enumeration, and keying. But Java people don't use identity as the equivalence relation between hash keys by default (which your traditional Lisp does), so they can just use strings as their keys. Enum types are defined separately in Scala. And finally, code as data isn't supported by the language at all.

So no, my impression is that symbols don't belong in the Scala language. That said, I'm going to keep an eye on the replies to this question. They might still demonstrate a genuine use of symbols in Scala that I can't think of right now.

(Addendum: Depending on the Lisp dialect, Lisp symbols may also be namespace-qualified, which is, of course, an immensely useful feature when manipulating code, and a feature that strings don't have.)

这篇关于在 Scala 中使用符号的实际例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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