Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am a Java developer and I want to know how I can use Scala in my Java programs?
Go read Daniel Spiewak's excellent blog series about Scala. With Scala you can keep:
all your Java libraries
all the advantages of running on a JVM (ubiquity, administrative tools, profiling, garbage collection etc)
But you can write Scala code:
more concise and clear than Java (especially using more functional style, such as in the collections library)
it has closures and functions as part of the language
it has operator overloading (from the perspective of usage)
it has mixins (i.e. interfaces which contain implementation)
Also, take a look at this recent news item post on Scala's site:
"Research: Programming Style and Productivity".
In his paper, Gilles Dubochet, describes how he investigated two aspects of programming style using eye movement tracking. He found that it is, on average, 30% faster to comprehend algorithms that use for-comprehensions and maps, as in Scala, rather than those with the iterative while-loops of Java.
And another key quote from the news item:
Alex McGuire, who writes mission critical projects in Scala for power trading companies, says of Scala "The conciseness means I can see more of a program on one screen. You can get a much better overview. When I have some mathematical model to write with Java I have to keep two models in my head, the mathematical model itself and the second a model of how to implement it in Java. With Scala one model, the mathematical one, will do. Much more productive.”
You an read the rest of the post and other linked items there.
UPDATED 2019
I can name some simple points in plain language from my limited experience:
Properties. C++ and Java had this notion of a public getter/setter function "property" wrapped around an internal class variable which led to large amounts of boilerplate code. C# formalized this as a real language feature and reduced much of the boilerplate in C# 3.0 with auto-implemented properties. Scala classes define trivial properties simply as regular read only vals or read/write vars. The class may later choose to replace those with get or get/set methods without affecting client code. For this, Scala provides the most elegant solution with the least language features and complexity.
Arrays use regular generics. In Java/C#, int[] is redundant and confusing vs List<int> or List<Int>. Worse, in Java, List<Int> has lots of runtime overhead, so many developers have to know to use int[]. Scala avoids that problem. Also, in Java/C#, arrays support (covariant) casting, which was a mistake, that they now can't fix because of legacy concerns.
Scala has better support for immutability. val is a basic language feature.
Scala lets if blocks, for-yield loops, and code in braces return a value. This is very elegant in many situations. A very small plus is that this eliminates the need for a separate ternary operator.
Scala has singleton objects rather than C++/Java/C# class static. This is a cleaner solution.
Pattern matching. Object unpacking. Very nice in a large numbers of situations.
Native tuples.
"case classes" which are what most other languages would call record types or named tuples.
Fancier standard library with more elegant collections.
Multi-line strings. String interpolation formatting.
Optional semi-colons.
Cons.
Java has caught up a lot. Java 8 was first released in 2014, but it took several years for older Java versions to be phased out and the new Java 8 features to be fully used across the Java ecosystem. Now, lambdas and closures and basic functional collections, with support for filter/map/fold are quite standard for the Java ecosystem. More recently, Java has added basic var local variable type inference and has multi-line strings and switch expressions in release builds preview mode.
Scala is complicated. I'd highlight features like implicits to be inherently confusing.
Scala has minimal backward compatibility. Scala 2.10 artifacts are incompatible with Scala 2.11.
Building a Java API for other JVM-language developers like Scala or Clojure or Kotlin is normal, well supported and accepted. You generally don't want to build APIs in Scala that cater to non-Scala developers.
I am not sure you can easily use Scala in your Java programs, as in "call a Scala class from a Java class".
You can try, following the article "Mixing Java and Scala".
Relevant extracts:
The problem is that the Java and Scala compilation steps are separate: you can't compile both Java and Scala files in one go.
If none of your Java files reference any Scala classes you can first compile all your Java classes, then compile your Scala classes.
Or, if none of your Scala files reference any Java classes you can do it the other way around.
But if you want your Java classes to have access to your Scala classes and also have Scala classes have access to your Java classes, that's a problem.
Scala code can easily call directly into Java code, but sometimes calling Scala code from Java code is trickier, since the translation from Scala into bytecode is not quite as straightforward as for Java:
sometimes the Scala compiler adds characters to symbols or makes other changes that must be explicitly handled when calling from Java.
But a Scala class can implement a Java interface, and an instance of that class can be passed to a Java method expecting an instance of the interface.
The Java class then calls the interface methods on that instance exactly as if it were a Java class instance.
The opposite is possible, of course, as described in Roundup: Scala for Java Refugees, from Daniel Spiewak.
Scala or Java:
Pros:
Scala supports both functional and imperative OO programming styles and it advocates that both models are not conflicting with each other but yet they are orthogonal and can complement each other. Scala doesn't require or force the programmer to use a particular style, but usually the standard is to use functional style with immutable variables when appropriate (there are several benefits of using the functional approach such as concise and short syntax and using pure functions usually reduces the amount of non-determinism and side-effects from the code), while resorting to imperative programming when the code would look simpler or more understandable.
Scala doesn't require ; at the end of each line having it optional which leads to cleaner code
In Scala functions are first class cititzens
Scala supports some advanced features which are directly built in the language such as: Currying, Closures, Higher order functions, pattern matching, Higher Kinded Types, Monads, implicit params.
Scala can interact very well with Java and both can coexist. It is possible to use java libraries directly inside Scala code invoking Java classes from scala code.
Has Tuples built in the language which makes life easier in several scenarios
Supports operator overloading
has a rich Ecosystem and some popular open source projects in Apache are based on it.
Async and Non-blocking code is very easy to write with Scala Futures
Scala supports the Actor model using Akka which can be highly efficient and scalable when running distributed applications in multi-threaded and parallel business use cases (Enforce encapsulation without resorting to locks, State of actors is local and not shared, changes and data is propagated via message)
Code tends to be shorter if compared to Java (might not be always the case)
Cons:
Steep learning curve if compared to Java and other languages, requires more time in general from the learner to understand all the concepts clearly. Has many features
It is not as well established as Java in the market since it was invented later so Java in overall is more mature and more battle-tested.
Scala opens too many doors. It allows a lot of complex syntax that if used in a irresponsible way might lead to code that is hard to understand.
Abusing things such as operator overloading, implicit params and other constructs can be counter-productive and might ruin code legibility.
Java is also evolving and still getting better with newer versions (such as with JDK 9 modules)
Related
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?
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:
Collections - Scala's are much better, and I would always prefer them over the Java equivalents. Scala does however lack a mutable TreeMap, so if you need that sort of structure you'll have to go back to Java.
Concurrency - Scala's concurrency features wrap Java's and are more advanced. I'd always pick them.
IO - I think this is one area where Scala is narrower in what it supports. I would generally use a Scala 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).
Swing - Last time I looked, Scala's swing wrapping wasn't complete, so if you're doing a lot of Swing related stuff, you might take the decision to use Java's swing components everywhere for consistency.
Scala Libraries fit into two general categories:
Original Scala Libraries. These are entirely (or almost entirely) written in Scala. Usually, people will write libraries from scratch for good reasons. Maybe Java lacks a similar library, or maybe whoever wrote the Scala one thinks the Java equivalent has serious limitations.
Collections is one such example.
Scala Wrappers over Java Libraries. In these cases, Scala uses an adapter pattern (or one of the other similar patterns) to provide a Scala-friendly API. These APIs are more fluent, integrate well with important Scala classes (such as collections and 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 than java.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's Process and ProcessBuilder, providing almost all of the functionality, and adding some. Furthermore, you can use most of Java internals if needed (the sole exception is Process 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.
From Clojure it is easy enough to use Java libraries...but what libraries does Clojure not have that are best done with Java?
It isn't easy to give a straightforward question to this answer, because it would be first necessary to define the difference between a Clojure library and a Java library. (Even more so, because Clojure is a Java library :))
Ok, let's start with a premise that a Clojure library is any library written in Clojure and simply ignore the Java code in Clojure implementation itself. But, what if given library uses some Java dependency, like say one of Apache Commons libraries? Would it still qualify as a Clojure and not Java library?
My own criterion (and I am guessing yours, too) for the difference between the two is whether or not the library exposes a Clojure-style interface with namespaces, functions, sequences or a Java-style interface with classes, methods and collections.
It is almost trivial to write Clojure wrappers around such Java libraries. In my experience that is very useful if you want to fit in functionality of the library in overall functional design of your application. A simple example would be if you want to map a Java method against a sequence. You can either use an ad-hoc defined anonymous function to wrap the method call, or a named function from your wrapper layer. If you do such things very often the second approach may be more suited, at least for most commonly used methods.
So, my conclusion is that any Java library should be easy to convert to a Clojure library. All that is needed is to write a wrapper for it.
Another conclusion is that it may not be needed at all. If all you want is to call the method, you may still just call the method and avoid all the architecture astronautics. :)
One potential answer may be a bytecode library like ASM http://asm.ow2.org/
But honestly, with time, any library in Java can be written in clojure. Some Java code that compiled to different bytecode can be replicated if clojure uses ASM underneath.
I strongly prefer Clojure as a language for development in general, but there are several good reasons I have found for using Java libraries or writing Java code in preference to Clojure:
Leveraging mature Java libraries - some Java libraries are truly excellent and very mature. From a pragmatic perspective, you are much better off directly using Java libraries like Netty, Swing or Joda Time rather than trying to utilise or invent some Clojure alternative. Sometimes there are Clojure wrappers for these libraries but these are mostly still in a somewhat experimental / immature state.
High performance code - I do quite a lot of data and image processing where maximum performance in essential. This rules out pretty much any approach that adds overhead (such as lazy sequences, temporary object creation) so idiomatic Clojure won't fit the bill. You could probably get there with very unidiomatic Clojure (lots of tight imperative loops and primitive array manipulation for example...) but if you're going to write this kind of code it's often actually simpler and cleaner in Java
APIs with mutable semantics - if the APIs you are relying upon depend upon mutable objects, Clojure code to interface with these APIs can become a bit ugly and unidiomatic. Sometimes writing Java in these cases is simpler.
The good news is that because the interoperability between Clojure and Java is so good, there isn't really any issue with mixing Clojure and Java code in a project. As a result, most of my projects are a mix of Clojure and Java code - I use whichever one is most appropriate for the task at hand.
Libraries for building GUIs comes to mind.
Lots of APIs. In fact, Clojure itself is built on top many sturdy Java APIs like the java.util.Collection API. And well known Clojure APIs like Incanter are built on top of libraries like Parallel Colt, and JFreeChart.
I can't find the quote at the moment; but Rich said somthing to the effect of "clojure should use java where possible" and not wrap java unnecessarily. The principal being to embrace the java platform instead of fighting it. so the general advice becomes:
If a good java library exists use it, if not write one in clojure.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
Is there a good library for functional programming in Java?
I'm looking for stuff like Predicate and List.Find() (as a static method). Not complicated to implement, but it would be nice to find a reusable library here.
FunctionalJava is the best known library; it makes use of Java closures (BGGA) for examples:
final Array<Integer> a = array(1, 2, 3);
final Array<Integer> b = a.map({int i => i + 42});
arrayShow(intShow).println(b); // {43,44,45}
EDIT
Check also lambdaj.
Further EDIT
BGGA is entirely optional. It just makes for nicer syntax.
Scala is a functional programming language that is fully compatible with Java (runs through the JVM). It offers a beautiful mix of object-oriented and functional techniques along with many improvements over Java in generics and concurrency. Some even say it could replace Java.
Java Libraries
There are libraries that can help you do this, by already doing the legwork for you and hiding the arcane things:
Mature / Established Libraries
Functional Java
Google guava
LambdaJ
More Obscure / Experimental Libraries
Fun4J
JCurry
OCaml-Java
Jambda
Bolts
These will allow you to write Java code with a more functional approach and possibly more familiar syntax and semantic, as you'd expect from an FP-competent language. Within reason, that is.
JVM Languages
And obviously, you can implement a functional language on top of Java. So that you can then use that one as your FP language. Which is a bit of a higher-level of abstraction than what you asked for, but relatively within context (though I'm cheating a bit here, granted).
For instance, check out:
Quite Mature Languages
Clojure
Scala
Less Mature or More Obscure Languages
Frege
Jaskell
Further Reading
You may also want to read or watch these articles or videos:
Functional Progamming in the Java Language, IBM DeveloperWorks (2004)
Functional Programming Java, Lambda the Ultimate (2004)
Functional Programming: a Pragmatic Introduction, InfoQ/CodePalousa (2011)
Taken from my P.SE answer to "Is Functional Programming Possible in Java?"
Google collections has a decent selection of functional-programming style utility methods.
Some classes of interest are Iterables, Iterators, Function, Functions, etc
It also has a bunch of collection classes as well!
Functional Java is one that's worth taking a look at and FunctionalJ is another.
If you want a pure Java solution check out lambdaj
http://code.google.com/p/lambdaj/
Besides the possibility to define and use closure in a DSL-style, it also allows to manipulate collections in a functional way, without explicitly write closures or loops
Jambda is another FP-library. From the documentation:
Jambda is an attempt to provide the
Java(TM) world with tools and concepts
from functional programming (FP).
The goals are several:
To provide Java programmers with expressive FP constructs
To provide a bridge for Java programmers into the FP-world
To see how far Java and generics can be stretched
This
document is an attempt to introduce
Java programmers into the FP world,
and at the same time explain some (or
most) of the features in Jambda.
Apache Commons has some functional-ish code in it. See for example, the Predicate interface.
Google Guava has functional:
collection operations
concurrency constructs (Futures)
Or download OpenJDK 8 to try out Lambda expressions the way they will become in Java 8. Among others, the collection APIs are adjusted to support a functional style. See
http://macgyverdev.blogspot.se/2012/10/functional-programming-in-java.html
for examples of new collection APIs and comparisons with Guava, LambdaJ and FunctionalJava.
Scala was mentioned here, but there's a lot lighter and more Java compatible language: Xtend. It compiles to plain Java and uses the same type system. It has great Eclipse support. You can mix .java and .xtend files in a single project.
Sample code:
def static void main(String[] args) {
val s = #[1,2,3].map[it+43].join(", ")
println(s);
}
Although Functional Java is the most popular but i'll suggest you to try Google guava lib.
http://code.google.com/p/guava-libraries/
I have an application written in C++ (makes heavy use of templates) that I need to take to the Java ME platform.
I have two questions:
Are there any good tools to convert C++ code to Java - do some basic stuff so I have a platform to start with. I found this - http://tangiblesoftwaresolutions.com/Product_Details/CPlusPlus_to_Java_Converter_Details.html. It would at least eliminate the need for simple but time-consuming stuff like moving classes to different files, namespaces to packages, etc. Has anyone tried it? Or knows of any better ones?
The bigger problem is how to deal with templates - the code makes very heavy use of them. Any suggestions on how to go about this? Are there any tools to expand templates for instance so I have a rudimentary base and then I could work on writing the modules in Java?
Any help would be appreciated.
For all of Sun's marketing, Java is not simply a better C++, and in fact does not support many of the idioms and paradigms C++ supports. This makes automated translation difficult. How should you automatically turn a multi-inheritance hierarchy into Java's single inheritance hierarchy? (Note, I am not saying that a multi-inheritance hierarchy is a good thing, only that it is explicitly allowed in C++). More fundamentally, how would you represent a pointer-to-member function in Java? Or handle the differences between Java and C++ overload resolution?
Java added generics a few years ago, but purposely made them less powerful than C++ templates. Regardless of whether that was a good idea, it limits what automated translation can do with heavily templatized code.
Aside from using some research compiler that can turn C++ into Java bytecode, I'm afraid you may be stuck doing the translation by hand.
Can you use JNI and call the old C++ code from the new Java code?
I think for your case a very simple tool would be possible and perhaps worthwhile. Might be a fun weekend-job, though! A friend of mine once did a port from C++ to Java and he just made a list of regular expression substitutions. Like, he had all occurrences of -> replaced by a dot. And so forth. This was some years ago, however, so I don't really feel like asking him.
So, you could do the same, collect some easy substitutions and perhaps publish them somewhere on github?
Generics is the Java feature that corresponds to C++ templates and they are not supported in J2ME. You can use them with the aid of a framework, which probably uses pre-processing to do the trick. (Actually Generics in Java is a compiler feature - the JVM knows nothing about them.)
Anyway, it will be difficult if not impossible to automatically port even a small portion of your code form C++ to Java Standard Edition - things are much worse with J2ME. There are many and important differences between Java Generics and C++ templates.
I don't think it's going to be possible, esp. if your original code is heavily templatized - J2ME doesn't support generics, AFAIK.
Unfortunately, it seems like this will require a lot of manual work to go through the original code and rewrite it (I'm assuming your target platform doesn't support JNI)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
What is the difference between Java and C++? Are both object-oriented?
This is far too general a question to be answered here.
Java is an explicitly object-oriented language, with the harder-to-use bits snipped off.
C++ is a multi-paradigm language with the safety off. You can do object-oriented programming in it, as well as procedural and generic.
If you had a more specific question, we could be of more help. Why did you ask? If you want recommendations for a particular platform, or project, or whatever, we could be more responsive.
A C++ programmer will tell you that Java is rubbish. A Java programmer will tell you that C++ is rubbish. Therefore I conclude that they are indeed the same thing.
Each language designed with different purposes in mind, so IMO it's not fair to compare the two from one perspective, and ignore the other.
Generally speaking, C++ is an open standard, designed for implementing high performance systems where speed and performance and critical, there are lots of impressing projects designed using this language like Phoenix Lander, Adobe Acrobat Reader and others. C++ gives the developer the ability to program using a very high level abstraction -using generics for example, and, when needed, go down deep to the bare metal of the machine -to handle an interrupt for instance.
Java was designed with other purposes in mind, when Sun was planning Oak (later called Java), it focused on web applications so it supported the language with a bunch of heavy libraries of easy-to-use interfaces considering that. and portability (Compile once, run anywhere) using JVM, which prevents the programmer from coding to specific machine, but instead coding to a sandbox which in turn runs the code on the hosting machine, and this has obviously negative reflections on performance/speed.
Comparison of those two language is a popular cause of debate between programmers, and this is due to their different working demands and nature, IMO every language has made mistakes in order to mature, for example, C++'s exported templates, and Java's lack of procedural programming (Big Mistake). plus, each one has its pros and cons regarding different aspects, hence the one that balance productivity/performance issue IS the right language.
For more information Wikipedia's comprehensive article on Comparison of Java and C++
It might be interesting to take a look at what languages are used (and being used) to create major systems (like Google) from here.
One of the most important differences hasn't been mentioned yet - one is compiled to machine code, the other is compiled to bytecode which is interpreted by a virtual machine.
Everything is Object in Java as everything is derived from java.lang.Object But this is not the case in C++
No pointers in Java whereas C++ has provide support for pointers
No destructors in java (Java has automatic garbage collection) but C++ has destructors to do that
Thread support is built in Java but not in C++
No scope resolution operator in Java
No Goto statement in Java
No Multiple Inheritance allowed in Java but C++ allows that
No operator overloading is allowed in Java but C++ allows that
Java is interpreted for most part and hence Platform independent
Both are object oriented but they are very different languages. This probably isn't the best forum to ask for the differences... I would suggest you look both up on Wikipedia and review the descriptions there. You will be able to see the differences very quickly for yourself.
I love c++ but unless you absolutely need to use c++ then use something else. When you need to use c++ then you will know the difference, Grasshopper.
(hint do not write device drivers, video decoders, encryption libraries, 3-d graphics engines or language run-time engines in java).
Yes, both are object oriented programming languages.
C++ is an evolution to C. Which was a system programming language. C++ Added many features to the language to make it object oriented. It became the mainstream programming language for that reason.
Java is an evolution of C++, with different goals ( cross platform for instance ). It remove some of the features that make C++ so hard to learn. Simplify others and remove others.
The main difference is C++ programs are compiled directly to machine code ( understood by the CPU ) while Java programs are compiled to be run in a "Virtual Machine" the JVM most of the cases. For these reasons java programs were interpreted by another program and at the beginning were veeeery slow programs. Nowadays the VM may optimize this code and make it run very very fast.
See this link.http://www.javacoffeebreak.com/articles/thinkinginjava/comparingc++andjava.html
Gross but accurate oversimplification: Java is easier. C++ is faster.
Just a quick addition to what David Thornley posted. C++ is a procedural language that supports Objects and OO design. Java is pure OO. Java does less but on more.