We all know that one can use Java libraries from Scala and vice versa. But even looking over the surface of Java SE and Scala standard library, we can notice that there are many parts in them that solve identical or at least similar problems. The trivial examples are collections, concurrency and IO. I am not an expert in either of two, but I suspect that in general Java SE is broader in size while Scala SL contains more conceptually advanced features (such as actors). The question is, if we have access to both libraries and have an opportunity to use both languages, are there some recommendations when we should choose Java SE features over Scala SL?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
In general, when writing in Scala, I would advise always using the Scala libraries over the Java ones. My advice on specific areas would be:
Source
when possible, but there may be more unusual situations where you'll have to drop back to Java IO (or possibly use a third party library).Scala Libraries fit into two general categories:
Collections is one such example.
Option
), and often make use of powerful Scala features such as traits to decrease boilerplate.These libraries rarely offer more functionality than what Java provides, but reduces boilerplate enormously and makes code using them more idiomatic. Often, however, they present just a subset of the total functionality provided by Java. Depending on the library, it may or may not be possible or easy to extend it by accessing the underlying Java classes.
Scala Swing is great example of these.
In the particular case of
scala.io
, that is not so much a library as a crude wrapper just to handle simple common scripting tasks with an idiomatic Scala API. It's adequate for that -- and certainly much kinder on my eyes thanjava.io
--, but not for any serious I/O. There's a real I/O library for Scala currently undergoing evaluation for adoption.Another example I like a lot if
scala.sys.process
. It wraps over Java'sProcess
andProcessBuilder
, providing almost all of the functionality, and adding some. Furthermore, you can use most of Java internals if needed (the sole exception isProcess
itself, which isn't really much useful).My advice is to use Scala libraries were they exist and fit your needs, extend them if they are mostly adequate, but reach for Java libraries without hesitation otherwise. After all, having a high degree of interoperability with Java is a key feature of Scala.