开发者

Why don't scala collections have any human-readable methods like .append, .push, etc

Scala colle开发者_JAVA百科ctions have a bunch of readable and almost readable operators like :+ and +:, but why aren't there any human readable synonyms like append?


All mutable collections in Scala have the BufferLike trait and it defines an append method.

Immutable collections do not have the BufferLike trait and hence only define the other methods that do not change the collection in place but generate a new one.


Symbolic method names allow the combination with the assignment operation =.

For instance, if you have a method ++ which creates a new collection, you can automatically use ++= to assign the new collection to some variable:

var array = Array(1,2,3)
array ++= Array(4,5,6)
// array is now Array(1,2,3,4,5,6)

This is not possible without symbolic method names.


In fact they often some human-readable synonyms:

  • foldLeft is equivalent to /:
  • foldRight is equivalent to :\

The remaining ones are addition operators, which are quite human readable as they are:

  • ++ is equivalent to java addAll
  • :+ is append
  • +: is prepend

The position of the semi-colon indicates the receiver instance.

Finally, some weird operators are legacies of other functional programming languages. Such as list construction (SML) or actor messaging (erlang).


Is it any different than any other language?

Let's take Java. What's the human readable version of +, -, * and / on int? Or, let's take String: what's the human readable version of +? Note that concat is not the same thing -- it doesn't accept non-String parameters.

Perhaps you are bothered by it because in Java -- unlike, say, C++ -- either things use exclusively non-alphabetic operators, or alphabetic operators -- with the exception of String's +.


The Scala standard library does not set out to be Java friendly. Instead, adapters are provided to convert between Java and Scala collections.

Attempting to provide a Java friendly API would not only constrain the choice of identifiers (or mandate that aliases should be provided), but also limit the way that generics and function types were used. Substantially more testing would be required to validate the design.

On the same topic, I remember some debate as to whether the 2.8 collections should implement java.util.Iterable.

http://scala-programming-language.1934581.n4.nabble.com/How-to-set-the-scale-for-scala-BigDecimal-s-method-td1948885.html

http://www.scala-lang.org/node/2177

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜