Practical examples of using symbols in Scala?

前端 未结 8 2141
借酒劲吻你
借酒劲吻你 2020-12-07 19:46

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 Ru

8条回答
  •  攒了一身酷
    2020-12-07 20:26

    According to the Scala book, Symbols are interned: "If you write the same symbol twice, both expressions will refer to the exact same Symbol object."

    In contrast, Strings are only interned if they appear in literal form (at least in Java they are, not entirely sure about Scala). So I guess if you do a lot of serialization of Strings that are then put into collections, you might use symbols instead and save yourself some memory.

    But I agree with skaffman, I'm not totally convinced of their use.

    (In Ruby, Symbols are, apart from the meta-programming example you give, often used as keys in Hashes. In Ruby this is useful because there, Strings are never interned: every String allocates new memory. In Scala it might be useful, as I mentioned, if you combine it with a lot of (de)serialization so the Java Strings don't get interned as well.)

提交回复
热议问题