Why is Scala's Addable deprecated?

后端 未结 2 1749
天涯浪人
天涯浪人 2021-02-18 23:30

I noticed that Addable is deprecated, while Subtractable is not. What\'s wrong with Addable, and why is Subtractable different?

相关标签:
2条回答
  • 2021-02-19 00:10

    The problem is that + is overloaded to concatenate String to non-strings. So, whenever you use the + method on a type that doesn't have it, you'll get an error message that is not related to the real problem: that the type you have isn't the one you expected.

    There's +: and :+ to replace it.

    0 讨论(0)
  • 2021-02-19 00:23

    Expanding on Daniel's answer, + is also a very bad operator to use for collection insertion. Mathematically, the + operator has a very conventional meaning, and part of that meaning is a guarantee of associativity. Unfortunately, associativity is a guarantee that doesn't make any sense at all when you're adding an Int to a Vector[Int]. As such, + was always a very confusing operator for anyone who had any algebraic training.

    +: and :+ are superior in several ways, not the least of which is that there is no expectation of associativity. In fact, the very asymmetry of the operators imply non-associativity, which is precisely their semantics. Also +: and :+ mirror each-other very nicely, and +: is right-associative, all of which conspires to provide a very natural API for collection prepend and append, respectively.

    0 讨论(0)
提交回复
热议问题