Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are there RichInt or RichX in Scala?

Tags:

scala

implicit

This is a simple question.

Why was not the method related to Int resided in Int?
Instead Scala bothers to put related methods into RichInt and rely on implicit conversion so as to have them work like methods of Int.

Why bother?

like image 209
WeiChing 林煒清 Avatar asked Apr 15 '15 15:04

WeiChing 林煒清


1 Answers

Scala doesn't exist in a vacuum. It was specifically designed to be hosted in an ecosystem / on a platform which was mostly designed for another language: the Java platform, the .NET platform, the ECMAScript platform, Cocoa, etc.

This means that in some cases compromises had to be made, in order to make Scala operate seamlessly, efficiently, and with high performance with the ecosystem, libraries and language of the host platform. That's why it has null, why it has classes (it could get by with just traits, and allow traits to have constructors), why it has packages (because they can be cleanly mapped to Java packages or .NET namespaces), why it doesn't have proper tail calls, doesn't have reified generics, etc. It's even why it has curly braces, not to make it easier to integrate with Java, but to make it easier to integrate with the brains of Java developers.

scala.Int is a fake class, it represents a native platform integer (primitive int in Java, System.Int32 in .NET, etc.) Being fake, it can't really have any methods other than the operations provided by the host environment.

The alternative would be to have all operations in the Int class and have the compiler know the difference between which methods are native and which aren't. But that's a special case, it makes more sense to concentrate efforts on making "enrich-my-library" fast in general, so that all programmers can benefit from those optimizations instead of spending time, money and resources on optimizations that only apply to twelve or so classes.

like image 72
Jörg W Mittag Avatar answered Oct 08 '22 10:10

Jörg W Mittag