Rectangle 27 44

Anyway, I think the main difference is that play 1.x tried to build it's own stack while escaping away from j2ee, now they are part of a new and alternative stack, based on scala, akka, sbt and with the support of a company like typesafe...

all answers are pertinent, but this one seems like the most complete so far. thank you

playframework - What are the major differences between Play Framework ...

playframework playframework-2.0
Rectangle 27 68

I never had time to play with clojure. But for scala vs groovy, this is words from James Strachan - Groovy creator

"Though my tip though for the long term replacement of javac is Scala. I'm very impressed with it! I can honestly say if someone had shown me the Programming in Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy."

You can read the whole story here

It should be mentioned that this statement is not saying that Scala is better than Groovy. James is also known for saying that if he had known how much trouble it is to create a language he would never had created one. Seen in this context it is clear why he wouldn't have developed Groovy then of course. And I dare to say he gave many good ideas, but he is not the creator of current Groovy. he left the project long before the 1.0 in 2007 and has no participated since then. There is at least as much without him in the project as there was with him.

And given that James Strachan is working actively on the Kotlin language, Scala apparently isn't impressive enough for him.

@bdkosher he's working on it because Scala is too impressive for the most programmers and [more importantly,] in some places too complicated, too

Scala vs. Groovy vs. Clojure - Stack Overflow

scala groovy clojure language-comparisons
Rectangle 27 875

Groovy is a dynamically typed language, whose syntax is very close to Java, with a number of syntax improvements that allow for lighter code and less boilerplate. It can run through an interpreter as well as being compiled, which makes it good for fast prototyping, scripts, and learning dynamic languages without having to learn a new syntax (assuming you know Java). As of Groovy 2.0, it also has growing support for static compilation. Groovy supports closures and has support for programming in a somewhat functional style, although it's still fairly far from the traditional definition of functional programming.

Clojure is a dialect of Lisp with a few advanced features like Software Transactional Memory. If you like Lisp and would like to use something like it under the JVM, Clojure is for you. It's possibly the most functional language running on the JVM, and certainly the most famous one. Also, it has a stronger emphasis on immutability than other Lisp dialects, which takes it closer to the heart of functional language enthusiasts.

Scala is a fully object oriented language, more so than Java, with one of the most advanced type systems available on non-research languages, and certainly the most advanced type system on the JVM. It also combines many concepts and features of functional languages, without compromising the object orientation, but its compromise on functional language characteristics put off some enthusiasts of the latter.

Groovy has good acceptance and a popular web framework in Grails. It also powers the Gradle build system, which is becoming a popular alternative to Maven. I personally think it is a language with limited utility, particularly as Jython and JRuby start making inroads on the JVM-land, compared to the others.

Clojure, even discounting some very interesting features, has a strong appeal just by being a Lisp dialect on JVM. It might limit its popularity, granted, but I expect it will have loyal community around it for a long time.

Scala can compete directly with Java, and give it a run for its money on almost all aspects. It can't compete in popularity at the moment, of course, and the lack of a strong corporate backing may hinder its acceptance on corporate environments. It's also a much more dynamic language than Java, in the sense of how the language evolves. From the perspective of the language, that's a good thing. From the perspective of users who plan on having thousands of lines of code written in it, not so.

As a final disclosure, I'm very familiar with Scala, and only acquainted with the other two.

Nice one. Although I have to say Scala has Lightbend corporate backing and is used by big names like LinkedIn, Twitter, Spark and lots of banks. Where I work we have a codebase of 11 milions lines of Scala, which is not a good idea but it works.

A very good comparison! Obviously biased in favor of Scala and (to a lesser extent) static typing, but quite nice none-the-less.

Very biased against Groovy. I'd add that Groovy is closest syntactically of all the alternate JVM languages to Java (except jJava ;-) and will be the easiest of them for most developers to pick up. It supports both dynamic and static typing. It also has cleaner integration with Java (Both Groovy calling Java classes and vice versa) than Scala or Closure. Pigeon-holing it by saying it's only good for prototyping, scripts and learning is really only the opinion of Daniel and in no way reflects how other people are using it.

@hohonuuli I said its syntax is very close to Java, endorsed Grails and indicated it was deficient in my opinion. But it doesn't support static typing, just a type annotation which doesn't really enforce type -- look it up. It might have slightly cleaner integration with Java than Scala, but most Scala programmers wouldn't even know it, as most stuff just works. I stand by my words -- it can't compete with Scala as far as static typing goes, Jython and JRuby are more popular dynamic languages, and it isn't really functional. It's only clear advantage is being a Java-like dynamic language.

String s = 42

Scala vs. Groovy vs. Clojure - Stack Overflow

scala groovy clojure language-comparisons
Rectangle 27 219

Scala evolved out of a pure functional language known as Funnel and represents a clean-room implementation of almost all Java's syntax, differing only where a clear improvement could be made or where it would compromise the functional nature of the language. Such differences include singleton objects instead of static methods, and type inference.

Much of this was based on Martin Odersky's prior work with the Pizza language. The OO/FP integration goes far beyond mere closures and has led to the language being described as post-functional.

Despite this, it's the closest to Java in many ways. Mainly due to a combination of OO support and static typing, but also due to a explicit goal in the language design that it should integrate very tightly with Java.

Groovy explicitly tackles two of Java's biggest criticisms by

  • being dynamically typed, which removes a lot of boilerplate and

It's perhaps syntactically closest to Java, not offering some of the richer functional constructs that Clojure and Scala provide, but still offering a definite evolutionary improvement - especially for writing script-syle programs.

Groovy has the strongest commercial backing of the three languages, mostly via springsource.

Clojure is a functional language in the LISP family, it's also dynamically typed.

Features such as STM support give it some of the best out-of-the-box concurrency support, whereas Scala requires a 3rd-party library such as Akka to duplicate this.

Syntactically, it's also the furthest of the three languages from typical Java code.

I also have to disclose that I'm most acquainted with Scala :)

I never heard of this Funnel language before. Thanks for filling a little gap in the historical record.

You can't really call Clojure a pure functional language. Its certainly possible to write imperative code.

Scala has built in the Akka library for actor based concurrency. It is no longer a 3rd party dependency.

Scala now has concurrent versions of most if not all collections built in. You don't have to write concurrent code, just use concurrent collections, and voila, concurrency.

@Orubel In bytecode, a scala class is identical to the equivalent Java class - types and all. As a case in point, the entire Akka Java API is written in Scala. So please explain what you mean by "can't integrate" here - because it reads like FUD to me.

To summarize that document: "Scala features that don't exist in Java can't be directly used in Java". However... abstract type members and higher-kinded types are fairly advanced features that you're certainly not forced to use! Java also can't use methods without parameters, builders, or extension modules from Groovy, thus also making Groovy "not tightly integrated" by your own definition.

Scala vs. Groovy vs. Clojure - Stack Overflow

scala groovy clojure language-comparisons
Rectangle 27 8

I'm reading the Pragmatic Programmers book "Groovy Recipes: Greasing the wheels of Java" by Scott Davis, Copyright 2008 and printed in April of the same year.

It's a bit out of date but the book makes it clear that Groovy is literally an extension of Java. I can write Java code that functions exactly like Java and rename the file *.groovy and it works fine. According to the book, the reverse is true if I include the requisite libraries. So far, experimentation seems to bear this out.

It's probably important to note that not all code will behave exactly the same. Some of these differences include the way in which Groovy understands single and double quotation marks and its preference for boxing over widening. Most code will work the same, though.

Scala vs. Groovy vs. Clojure - Stack Overflow

scala groovy clojure language-comparisons
Rectangle 27 30

They can be differentiated with where they are coming from or which developers they're targeting mainly.

Groovy is a bit like scripting version of Java. Long time Java programmers feel at home when building agile applications backed by big architectures. Groovy on Grails is, as the name suggests similar to the Rails framework. For people who don't want to bother with Java's verbosity all the time.

Scala is an object oriented and functional programming language and Ruby or Python programmers may feel more closer to this one. It employs quite a lot of common good ideas found in these programming languages.

Clojure is a dialect of the Lisp programming language so Lisp, Scheme or Haskell developers may feel at home while developing with this language.

Scala isn't really a functional programming language. It is an object oriented programming language first, with functional features.

I have to say, this answer feels a lot like a shot in the dark. I think a good case could be made that Python is closer to Groovy than to Scala, and Ruby is (in my opinion) not too close to any of the above, perhaps closest again to Groovy. Haskell is not too much like (Common) Lisp or Scheme (and thus not much like Clojure). To me, this answer feels (at best!) like "I don't know either, let me Wikipedia that for you".

Scala is an imperative language with some functional features. If people continue to call a language functional as soon as it adopts idioms from the functional world then the term will become just another marketing term. Might as well start calling C++ functional and Haskell imperative.

@alanlcode Odersky may say what he wants. Scala doesn't have any system to isolate side effects, it isn't lazy by default, and doesn't treat code as data -- it treats function calls as data, which is different. These are big problems if you want to be fully functional. On the other hand, Scala goes all the way to ensure its Object Model isn't flawed. I love Scala, but it's clearly functional second.

On the other hand, the ML family of languages is recognized as functional but is strict and allow side effects/imperative code.

Scala vs. Groovy vs. Clojure - Stack Overflow

scala groovy clojure language-comparisons
Rectangle 27 6

Options are actually quite useful. In Java, it's tough to document whether or not something can be null. In Scala, you can often assume all variables are not null.

This gets really useful when you have some computation that can fail or may not be defined. A good instance would be if you have a webapp and there's some user data that isn't filled out, so the computation can't run. If you had the user data in a map, you could do something like

val myData = map.get(userId).map(doFunction).map(toHtml)
println(myData.getOrElse(noDataHtml))

So clearly here we never have to worry about null. If the user data is in the map, we proceed with the computation and then turn that into html. Otherwise, we'll just print out a default html. In Java, at each stage we'd have to do a null check, but in Scala we can just chain functions.

Scala Option vs Java null - Stack Overflow

scala
Rectangle 27 4

Obviously, the syntax are completely different (Groovy is closest to Java), but I suppose that is not what you are asking for.

If you are interested in using them to script a Java application, Scala is probably not a good choice, as there is no easy way to evaluate it from Java, whereas Groovy is especially suited for that purpose.

I don't understand your point about using Scala to script Java. You can certainly write a Scala script that drives Java code; no eval required.

@Daniel, please see the question about using Scala for scripting that I linked. The accepted answer there is that the lack of an "eval" facility and javax.scripting support makes it trickier to use Scala to script a Java application then it is with, say, Groovy.

Scala vs. Groovy vs. Clojure - Stack Overflow

scala groovy clojure language-comparisons
Rectangle 27 198

As already said in the previous posts, JIT can compile IL/bytecode into native code at runtime. The cost of that was mentionned, but not to its conclusion:

JIT has one massive problem is that it can't compile everything: JIT compiling takes time, so the JIT will compile only some parts of the code, whereas a static compiler will produce a full native binary: For some kind of programs, the static compiler will simply easily outperform the JIT.

Of course, C# (or Java, or VB) is usually faster to produce viable and robust solution than is C++ (if only because C++ has complex semantics, and C++ standard library, while interesting and powerful, is quite poor when compared with the full scope of the standard library from .NET or Java), so usually, the difference between C++ and .NET or Java JIT won't be visible to most users, and for those binaries that are critical, well, you can still call C++ processing from C# or Java (even if this kind of native calls can be quite costly in themselves)...

Note that usually, you are comparing C++ runtime code with its equivalent in C# or Java. But C++ has one feature that can outperform Java/C# out of the box, that is template metaprograming: The code processing will be done at compilation time (thus, increasing vastly compilation time), resulting into zero (or almost zero) runtime.

C++ has a memory usage different from Java/C#, and thus, has different advantages/flaws.

No matter the JIT optimization, nothing will go has fast as direct pointer access to memory (let's ignore for a moment processor caches, etc.). So, if you have contiguous data in memory, accessing it through C++ pointers (i.e. C pointers... Let's give Caesar its due) will goes times faster than in Java/C#. And C++ has RAII, which makes a lot of processing a lot easier than in C# or even in Java. C++ does not need using to scope the existence of its objects. And C++ does not have a finally clause. This is not an error.

And despite C# primitive-like structs, C++ "on the stack" objects will cost nothing at allocation and destruction, and will need no GC to work in an independent thread to do the cleaning.

As for memory fragmentation, memory allocators in 2008 are not the old memory allocators from 1980 that are usually compared with a GC: C++ allocation can't be moved in memory, true, but then, like on a Linux filesystem: Who needs hard disk defragmenting when fragmentation does not happen? Using the right allocator for the right task should be part of the C++ developer toolkit. Now, writing allocators is not easy, and then, most of us have better things to do, and for the most of use, RAII or GC is more than good enough.

Now, the memory model is somewhat becoming more complicated with the rise of multicore and multithreading technology. In this field, I guess .NET has the advantage, and Java, I was told, held the upper ground. It's easy for some "on the bare metal" hacker to praise his "near the machine" code. But now, it is quite more difficult to produce better assembly by hand than letting the compiler to its job. For C++, the compiler became usually better than the hacker since a decade. For C# and Java, this is even easier.

Still, the new standard C++0x will impose a simple memory model to C++ compilers, which will standardize (and thus simplify) effective multiprocessing/parallel/threading code in C++, and make optimizations easier and safer for compilers. But then, we'll see in some couple of years if its promises are held true.

Last week, I had a training on .NET optimization, and discovered that the static compiler is very important anyway. As important than JIT.

The very same code compiled in C++/CLI (or its ancestor, Managed C++) could be times faster than the same code produced in C# (or VB.NET, whose compiler produces the same IL than C#).

Because the C++ static compiler was a lot better to produce already optimized code than C#'s.

For example, function inlining in .NET is limited to functions whose bytecode is less or equal than 32 bytes in length. So, some code in C# will produce a 40 bytes accessor, which won't be ever inlined by the JIT. The same code in C++/CLI will produce a 20 bytes accessor, which will be inlined by the JIT.

Another example is temporary variables, that are simply compiled away by the C++ compiler while still being mentioned in the IL produced by the C# compiler. C++ static compilation optimization will result in less code, thus authorizes a more aggressive JIT optimization, again.

The reason for this was speculated to be the fact C++/CLI compiler profited from the vast optimization techniques from C++ native compiler.

But as far as I see it, C# or Java are all in all a better bet. Not because they are faster than C++, but because when you add up their qualities, they end up being more productive, needing less training, and having more complete standard libraries than C++. And as for most of programs, their speed differences (in one way or another) will be negligible...

I have now 5 months of almost exclusive professional C# coding (which adds up to my CV already full of C++ and Java, and a touch of C++/CLI).

I played with WinForms (Ahem...) and WCF (cool!), and WPF (Cool!!!! Both through XAML and raw C#. WPF is so easy I believe Swing just cannot compare to it), and C# 4.0.

The conclusion is that while it's easier/faster to produce a code that works in C#/Java than in C++, it's a lot harder to produce a strong, safe and robust code in C# (and even harder in Java) than in C++. Reasons abound, but it can be summarized by:

Generics are not as powerful as templates

C# readonly and Java final are nowhere as useful as C++'s const

So, C# remains an pleasant language as long as you want something that works, but a frustrating language the moment you want something that always and safely works.

Java is even more frustrating, as it has the same problems than C#, and more: Lacking the equivalent of C#'s using keyword, a very skilled colleague of mine spent too much time making sure its resources where correctly freed, whereas the equivalent in C++ would have been easy (using destructors and smart pointers).

So I guess C#/Java's productivity gain is visible for most code... until the day you need the code to be as perfect as possible. That day, you'll know pain. (you won't believe what's asked from our server and GUI apps...).

I kept contact with the server teams (I worked 2 years among them, before getting back to the GUI team), at the other side of the building, and I learned something interesting.

Last years, the trend was to have the Java server apps be destined to replace the old C++ server apps, as Java has a lot of frameworks/tools, and is easy to maintain, deploy, etc. etc..

...Until the problem of low-latency reared its ugly head the last months. Then, the Java server apps, no matter the optimization attempted by our skilled Java team, simply and cleanly lost the race against the old, not really optimized C++ server.

Currently, the decision is to keep the Java servers for common use where performance while still important, is not concerned by the low-latency target, and aggressively optimize the already faster C++ server applications for low-latency and ultra-low-latency needs.

Nothing is as simple as expected.

Java, and even more C#, are cool languages, with extensive standard libraries and frameworks, where you can code fast, and have result very soon.

But when you need raw power, powerful and systematic optimizations, strong compiler support, powerful language features and absolute safety, Java and C# make it difficult to win the last missing but critical percents of quality you need to remain above the competition.

It's as if you needed less time and less experienced developers in C#/Java than in C++ to produce average quality code, but in the other hand, the moment you needed excellent to perfect quality code, it was suddenly easier and faster to get the results right in C++.

But still, it is what happens today, both in the GUI teams and the server-side teams.

Of course, I'll update this post if something new happens.

"We find that in regards to performance, C++ wins out by a large margin. However, it also required the most extensive tuning efforts, many of which were done at a level of sophistication that would not be available to the average programmer.

[...] The Java version was probably the simplest to implement, but the hardest to analyze for performance. Specifically the effects around garbage collection were complicated and very hard to tune."

"The going word at Facebook is that 'reasonably written C++ code just runs fast,' which underscores the enormous effort spent at optimizing PHP and Java code. Paradoxically, C++ code is more difficult to write than in other languages, but efficient code is a lot easier [to write in C++ than in other languages]."

You edit after 5 months of C# describes exactly my own experience (templates better, const better, RAII). +1. Those three remain my personal killer features for C++ (or D, which I hadn't the time for, yet).

"The code processing will be done at compilation time". Hence template metaprogramming only works in the program is available at compile time which is often not the case, e.g. it is impossible to write a competitively performant regular expression library in vanilla C++ because it is incapable of run-time code generation (an important aspect of metaprogramming).

"playing with types is done at compile time...the equivalent in Java or C# is painful at best to write, and will always be slower and resolved at runtime even when the types are known at compile time". In C#, that is only true of reference types and is not true for value types.

"No matter the JIT optimization, nothing will go has fast as direct pointer access to memory...if you have contiguous data in memory, accessing it through C++ pointers (i.e. C pointers... Let's give Caesar its due) will goes times faster than in Java/C#". People have observed Java beating C++ on the SOR test from the SciMark2 benchmark precisely because pointers impede aliasing-related optimizations. blogs.oracle.com/dagastine/entry/sun_java_is_faster_than

C++ performance vs. Java/C# - Stack Overflow

c# java c++ performance bytecode
Rectangle 27 433

There are two aspects to the (lack of) speed for the Scala compiler.

Overall, expect a startup overhead of scalac of 4-8 seconds, longer if you run it the first time so disk-caches are not filled.

On the other hand, a 1000 line Scala program might correspond to a 2-3K line Java program, so some of the slower speed when counted in lines per second has to balanced against more functionality per line.

We are working on speed improvements (for instance by generating class files in parallel), but one cannot expect miracles on this front. Scalac will never be as fast as javac. I believe the solution will lie in compile servers like fsc in conjunction with good dependency analysis so that only the minimal set of files has to be recompiled. We are working on that, too.

I think that the problem is with Idea, not the scala compiler itself. Somehow it is much slower

About the startup overhead due to class loading: would ahead-of-time compiling to native code using GCJ or Mono help?

What if Scala were rewritten in C++? :o)

Would there be a benefit to using the invokedynamic bytecode instruction?

performance - Java compile speed vs Scala compile speed - Stack Overfl...

java performance scala compilation
Rectangle 27 54

The Scala compiler is more sophisticated than Java's, providing type inference, implicit conversion, and a much more powerful type system. These features don't come for free, so I wouldn't expect scalac to ever be as fast as javac. This reflects a trade-off between the programmer doing the work and the compiler doing the work.

That said, compile times have already improved noticeably going from Scala 2.7 to Scala 2.8, and I expect the improvements to continue now that the dust has settled on 2.8. This page documents some of the ongoing efforts and ideas to improve the performance of the Scala compiler.

I've switched from netbeans to ant+jedit(I know I know, ant is for cavemen, but I'll evolve on my own time) so that I can use fsc. But I was wondering, how does the compile speed of Clojure compare to Scala? It seems to have many of the features in Scala but I imagine the syntax is much easier to parse.

We're kinda getting off-topic here, but Clojure's compiler is blisteringly fast (much faster than javac on equivalent sources). You're right that it's a really simple language though, and it doesn't have any sort of static type system, which helps quite a bit.

performance - Java compile speed vs Scala compile speed - Stack Overfl...

java performance scala compilation
Rectangle 27 11

So if call by need (lazy) does as much or less evaluation (as either o...

There is some breadth in the names given to the evaluation strategies, but they come down to roughly this:

call by name an argument is pretty much just substituted into the function body in whatever (unevaluated) form it was in when the function was called. That means it may need to be evaluated multiple times in the body.

scala> def f(x:=> Int): Int = x + x
scala> f({ println("evaluated"); 1 })
evaluated
evaluated
2

In Haskell you have no built in way of doing this, but you could always represent call-by-name values as functions of type () -> a. This is a bit more blurry though, because of referential transparency - you won't be able to test this out the way you would with Scala (and the compiler might optimize away the "by name" part of your call).

call by need (lazy... sort of) an argument is not evaluated when the function is called, but on the first time is is needed. At that moment, it is also cached. Afterwards, whenever the argument is needed again, the cached value is looked up.

In Scala, you don't declare your function arguments to be lazy, you make a declaration lazy:

scala> lazy x: Int = { println("evaluated"); 1 }
scala> x + x
evaluated
2

In Haskell this is how all functions work by default.

call by value (eager, what almost every language does) arguments are evaluated when the function is called, even if the function doesn't end up using those arguments.

In Scala this is how functions work by default.

scala> def f(x: Int): Int = x + x
scala> f({ println("evaluated"); 1 })
evaluated
2

In Haskell, you can force this behaviour with bang patterns on function arguments:

ghci> :{
ghci> f :: Int -> Int
ghci> f !x = x
ghci> :}

Lazy evaluation is tough to reason about unless you have referential transparency, because then you need to figure out exactly when your lazy value was evaluated. Since Scala is built to interoperate with Java, it needs to support imperative, side-effectful programming. As a consequence, it is in many cases not a good idea to use lazy in Scala.

Furthermore, lazy has a performance overhead: you need to have an extra indirection to check if the value has been already evaluated or not. In Scala, that translates to a bunch more objects, which puts an even greater strain on the garbage collector.

Finally, there are cases where having lazy evaluation leaves "space" leaks. For example, in Haskell, folding a large list of numbers from the right by adding them together is a bad idea because Haskell will build up this gigantic series of lazy calls to (+) before evaluating them (when in reality you just need it to have an accumulator. A famous example of space issues you get even in simple contexts is foldr vs foldl vs foldl'.

Apart from caching, aren't call by name and call by need equivalent?

@max Sort of... Minus the fact that call-name in Scala is only supported at call site as opposed lazy is supported at definition site only

Also, quoting @user7337271 answer: in Haskell side effects are explicit. Scala is much more pragmatic and there is no explicit way to model side effects; is this the main reason Scala chose its default evaluation to be call-by-name rather than call-by-need (given that functions with side effects cannot be memoized)? Or was it also due to space or other considerations?

@max, well, in a language with side-effects, you might not want caching. For example if you're writing a function which is supposed to evaluate its argument multiple times, e.g. some kind of looping function. If the function wants to cache it it always can explicitly, whereas you can't go the other way around. Call-by-name is thereby more expressive. In Haskell this is not done because functions do not have side-effects, so there is no difference in expressiveness and you might as well cache to save work.

@max Scala chose its default evaluation to be call-by-value, not call-by-name. In general, call-by-value is easier to reason about when you have side-effects. Since Scala wanted to interop with Java, side-effects are sort of necessary.

Call-by-name in Scala vs lazy evaluation in Haskell? - Stack Overflow

scala haskell lazy-evaluation evaluation
Rectangle 27 39

You should be aware that Scala compilation takes at least an order of magnitude longer than Java to compile. The reasons for this are as follows:

XY.scala
XY
  • Implicits - heavy use of implicits means the compiler needs to search any in-scope implicit conversion for a given method and rank them to find the "right" one. (i.e. the compiler has a massively-increased search domain when locating a method.)
  • The type system - the scala type system is way more complicated than Java's and hence takes more CPU time.
  • Type inference - type inference is computationally expensive and a job that javac does not need to do at all
  • scalac includes an 8-bit simulator of a fully armed and operational battle station, viewable using the magic key combination CTRL-ALT-F12 during the GenICode compilation phase.

You weren't supposed to talk about the battle station!

int a<T>(T a) {}
a(pls_infer_my_type)

performance - Java compile speed vs Scala compile speed - Stack Overfl...

java performance scala compilation
Rectangle 27 71

I think either language will be fast enough for you. When comparing Python and Java, it seems a bit unreasonable to blame the language for the speed difference. Java is compiled JIT (except on mobile devices*) whereas Python is interpreted. Just because both use a bytecode does not mean the implementations will have even remotely comparable performance. But both Scala and Clojure are JVM languages so they should have similar performance.

Scala has a few implementation advantages over Clojure and I would expect somewhat higher performance. Although Scala's static typing would normally translate into a speed advantage over Clojure's duck typing, Clojure does support type hinting which can speed up code considerably. Possibly, ordinary Scala is faster than ordinary Clojure, but you only need to optimize the bottlenecks. Most of a program's run time is generated by a small amount of the actual code.

Regarding interop w/ Java, Scala is closer to Java but I'm sure both languages interoperate well. In Programming Clojure Stuart Halloway writes: "[you can access] anything you could reach from Java code.".

And since Scala author Martin Odersky wrote Sun's Java compiler, I kinda think no balls have been dropped on the Scala side, either. :-)

You would be hard-pressed to pick two better languages, though I like Ruby also. Why are you worried about which one to try? Why not try them both? Scala is more likely to be "the next Java", while it's hard to imagine that Lisp will finally take off after not doing so for over 50 years. But it's clear that Lisp is on its own unique level of abstraction, and Clojure is fairly simple, so Scala + Clojure won't be that much harder than just (the rather complex) Scala and I'm sure you will be glad you did it.

* dalvik (android's JVM) got a JIT compiler in 2.2 version in 2010

Huh. Well, thanks for all of the insights. At first, I was in the mode where I wanted to just pick one and run with it. But for some reason, it didn't occur to me that I could just use both and have them inter-operate. So, perhaps I'll pick both and do a fast-walk with them :-)

And I'd like to add that I do have a bit of a "soft spot" for LISP so the fact that Clojure suffers from parethesitis isn't enough to scare me away.

It's not always true that a language written in the JVM will perform at top speed. The original JRuby had abysmal performance because it was an interpreter that was compiled to the JVM, not the source code. The language, also, can be to blame. Statically typed languages are often easier to optimize than dynamic languages, etc.

-1 "both Scala and Clojure are JVM languages so they should have similar performance" makes absolutely no sense. Dynamic languages that need to stay interoperable with a static languages like Java are always much slower (overloading comes at a huge cost, type hinting doesn't solve all the problems, etc.)

@julkiewicz - it is simply not true that dynamic languages are always much slower. It depends on whether your compiler can do a decent job of optimising the code in question. For example, in Clojure you can do arithmetic with Java primitives that exactly matches Java performance. Likewise, calling a method on a type-hinted Java object is as fast as a Java object method call. The Clojure compiler essentially produces the same bytecode as javac would for equivalent Java code.

On Performance and Java Interoperability: Clojure vs. Scala - Stack Ov...

java performance scala clojure jvm
Rectangle 27 71

I think either language will be fast enough for you. When comparing Python and Java, it seems a bit unreasonable to blame the language for the speed difference. Java is compiled JIT (except on mobile devices*) whereas Python is interpreted. Just because both use a bytecode does not mean the implementations will have even remotely comparable performance. But both Scala and Clojure are JVM languages so they should have similar performance.

Scala has a few implementation advantages over Clojure and I would expect somewhat higher performance. Although Scala's static typing would normally translate into a speed advantage over Clojure's duck typing, Clojure does support type hinting which can speed up code considerably. Possibly, ordinary Scala is faster than ordinary Clojure, but you only need to optimize the bottlenecks. Most of a program's run time is generated by a small amount of the actual code.

Regarding interop w/ Java, Scala is closer to Java but I'm sure both languages interoperate well. In Programming Clojure Stuart Halloway writes: "[you can access] anything you could reach from Java code.".

And since Scala author Martin Odersky wrote Sun's Java compiler, I kinda think no balls have been dropped on the Scala side, either. :-)

You would be hard-pressed to pick two better languages, though I like Ruby also. Why are you worried about which one to try? Why not try them both? Scala is more likely to be "the next Java", while it's hard to imagine that Lisp will finally take off after not doing so for over 50 years. But it's clear that Lisp is on its own unique level of abstraction, and Clojure is fairly simple, so Scala + Clojure won't be that much harder than just (the rather complex) Scala and I'm sure you will be glad you did it.

* dalvik (android's JVM) got a JIT compiler in 2.2 version in 2010

Huh. Well, thanks for all of the insights. At first, I was in the mode where I wanted to just pick one and run with it. But for some reason, it didn't occur to me that I could just use both and have them inter-operate. So, perhaps I'll pick both and do a fast-walk with them :-)

And I'd like to add that I do have a bit of a "soft spot" for LISP so the fact that Clojure suffers from parethesitis isn't enough to scare me away.

It's not always true that a language written in the JVM will perform at top speed. The original JRuby had abysmal performance because it was an interpreter that was compiled to the JVM, not the source code. The language, also, can be to blame. Statically typed languages are often easier to optimize than dynamic languages, etc.

-1 "both Scala and Clojure are JVM languages so they should have similar performance" makes absolutely no sense. Dynamic languages that need to stay interoperable with a static languages like Java are always much slower (overloading comes at a huge cost, type hinting doesn't solve all the problems, etc.)

@julkiewicz - it is simply not true that dynamic languages are always much slower. It depends on whether your compiler can do a decent job of optimising the code in question. For example, in Clojure you can do arithmetic with Java primitives that exactly matches Java performance. Likewise, calling a method on a type-hinted Java object is as fast as a Java object method call. The Clojure compiler essentially produces the same bytecode as javac would for equivalent Java code.

On Performance and Java Interoperability: Clojure vs. Scala - Stack Ov...

java performance scala clojure jvm
Rectangle 27 51

Summary: There are three basic patterns for attempting to reproduce the Java Enum within a Scala project. Two of the three patterns; directly using Java Enum and scala.Enumeration, are not capable of enabling Scala's exhaustive pattern matching. And the third one; "sealed trait + case object", does...but has JVM class/object initialization complications resulting in inconsistent ordinal index generation.

I have created a solution with two classes; Enumeration and EnumerationDecorated, located in this Gist. I didn't post the code into this thread as the file for Enumeration was quite large (+400 lines - contains lots of comments explaining implementation context). Details: The question you're asking is pretty general; "...when to use caseclassesobjects vs extending [scala.]Enumeration". And it turns out there are MANY possible answers, each answer depending on the subtleties of the specific project requirements you have. The answer can be reduced down to three basic patterns.

To start, let's make sure we are working from the same basic idea of what an enumeration is. Let's define an enumeration mostly in terms of the Enum provided as of Java 5 (1.5):

  • There is a fixed number of members
  • Each member has a unique name within the total set of all members
  • All members can easily be iterated through based on their indexes
  • It would be quite nice if a member could also be retrieved with its case insensitive name
  • A member can be retrieved with its index
  • Thinking beyond Java's Enum, it would be nice to be able to explicitly leverage Scala's pattern matching exhaustiveness checking for an enumeration

Next, let's look at boiled down versions of the three most common solution patterns posted: A) Actually directly using Java Enum pattern (in a mixed Scala/Java project):

public enum ChessPiece {
    KING('K', 0)
  , QUEEN('Q', 9)
  , BISHOP('B', 3)
  , KNIGHT('N', 3)
  , ROOK('R', 5)
  , PAWN('P', 1)
  ;

  private char character;
  private int pointValue;

  private ChessPiece(char character, int pointValue) {
    this.character = character; 
    this.pointValue = pointValue;   
  }

  public int getCharacter() {
    return character;
  }

  public int getPointValue() {
    return pointValue;
  }
}

For my current projects, I don't have the benefit of taking the risks around the Scala/Java mixed project pathway. And even if I could choose to do a mixed project, item 7 is critical for allowing me to catch compile time issues if/when I either add/remove enumeration members, or am writing some new code to deal with existing enumeration members.B) Using the "sealed trait + case objects" pattern:

sealed trait ChessPiece {def character: Char; def pointValue: Int}
object ChessPiece {
  case object KING extends ChessPiece {val character = 'K'; val pointValue = 0}
  case object QUEEN extends ChessPiece {val character = 'Q'; val pointValue = 9}
  case object BISHOP extends ChessPiece {val character = 'B'; val pointValue = 3}
  case object KNIGHT extends ChessPiece {val character = 'N'; val pointValue = 3}
  case object ROOK extends ChessPiece {val character = 'R'; val pointValue = 5}
  case object PAWN extends ChessPiece {val character = 'P'; val pointValue = 1}
}
  • 1.2 - Members are naturally ordered and explicitly indexed
  • 2 - All members can easily be iterated through based on their indexes
  • 3 - A member can be retrieved with its (case sensitive) name

It's arguable it really meets enumeration definition items 5 and 6. For 5, it's a stretch to claim it's efficient. For 6, it's not really easy to extend to hold additional associated singleton-ness data.C) Using the scala.Enumeration pattern (inspired by this StackOverflow answer):

object ChessPiece extends Enumeration {
  val KING = ChessPieceVal('K', 0)
  val QUEEN = ChessPieceVal('Q', 9)
  val BISHOP = ChessPieceVal('B', 3)
  val KNIGHT = ChessPieceVal('N', 3)
  val ROOK = ChessPieceVal('R', 5)
  val PAWN = ChessPieceVal('P', 1)
  protected case class ChessPieceVal(character: Char, pointValue: Int) extends super.Val()
  implicit def convert(value: Value) = value.asInstanceOf[ChessPieceVal]
}

The following items from the enumeration definition are not available (happens to be identical to the list for directly using the Java Enum):

  • 3.1 - It would be quite nice if a member could also be retrieved with its case insensitive name
  • 7 - Thinking beyond Java's Enum, it would be nice to be able to explicitly leverage Scala's pattern matching exhaustiveness checking for an enumeration

Again for my current projects, item 7 is critical for allowing me to catch compile time issues if/when I either add/remove enumeration members, or am writing some new code to deal with existing enumeration members.

So, given the above definition of an enumeration, none of the above three solutions work as they do not provide everything outlined in the enumeration definition above:

  • Java Enum directly in a mixed Scala/Java project

Each of these solutions can be eventually reworked/expanded/refactored to attempt to cover some of each one's missing requirements. However, neither the Java Enum nor the scala.Enumeration solutions can be sufficiently expanded to provide item 7. And for my own projects, this is one of the more compelling values of using a closed type within Scala. I strongly prefer compile time warnings/errors to indicate I have a gap/issue in my code as opposed to having to glean it out of a production runtime exception/failure.

In that regard, I set about working with the case object pathway to see if I could produce a solution which covered all of the enumeration definition above. The first challenge was to push through the core of the JVM class/object initialization issue (covered in detail in this StackOverflow post). And I was finally able to figure out a solution.

As my solution is two traits; Enumeration and EnumerationDecorated, and since the Enumeration trait is over +400 lines long (lots of comments explaining context), I am forgoing pasting it into this thread (which would make it stretch down the page considerbly). For details, please jump directly to the Gist.

Here's what the solution ends up looking like using the same data idea as above (fully commented version available here) and implemented in EnumerationDecorated.

import scala.reflect.runtime.universe.{TypeTag,typeTag}
import org.public_domain.scala.utils.EnumerationDecorated

object ChessPiecesEnhancedDecorated extends EnumerationDecorated {
  case object KING extends Member
  case object QUEEN extends Member
  case object BISHOP extends Member
  case object KNIGHT extends Member
  case object ROOK extends Member
  case object PAWN extends Member

  val decorationOrderedSet: List[Decoration] =
    List(
        Decoration(KING,   'K', 0)
      , Decoration(QUEEN,  'Q', 9)
      , Decoration(BISHOP, 'B', 3)
      , Decoration(KNIGHT, 'N', 3)
      , Decoration(ROOK,   'R', 5)
      , Decoration(PAWN,   'P', 1)
    )

  final case class Decoration private[ChessPiecesEnhancedDecorated] (member: Member, char: Char, pointValue: Int) extends DecorationBase {
    val description: String = member.name.toLowerCase.capitalize
  }
  override def typeTagMember: TypeTag[_] = typeTag[Member]
  sealed trait Member extends MemberDecorated
}

This is an example usage of a new pair of enumeration traits I created (located in this Gist) to implement all of the capabilities desired and outlined in the enumeration definition.

One concern expressed is that the enumeration member names must be repeated (decorationOrderedSet in the example above). While I did minimize it down to a single repetition, I couldn't see how to make it even less due to two issues:

  • JVM object/class initialization for this particular object/case object model is undefined (see this Stackoverflow thread)
  • The content returned from the method getClass.getDeclaredClasses has an undefined order (and it is quite unlikely to be in the same order as the case object declarations in the source code)

Given these two issues, I had to give up trying to generate an implied ordering and had to explicitly require the client define and declare it with some sort of ordered set notion. As the Scala collections do not have an insert ordered set implementation, the best I could do was use a List and then runtime check that it was truly a set. It's not how I would have preferred to have achieved this.

And given the design required this second list/set ordering val, given the ChessPiecesEnhancedDecorated example above, it was possible to add case object PAWN2 extends Member and then forget to add Decoration(PAWN2,'P2', 2) to decorationOrderedSet. So, there is a runtime check to verify that the list is not only a set, but contains ALL of the case objects which extend the sealed trait Member. That was a special form of reflection/macro hell to work through. Please leave comments and/or feedback on the Gist.

org.scalaolio.util.EnumerationDecorated

It looks like Odersky is wanting to upgrade Dotty (future Scala 3.0) with a native enum. Whoohoo! github.com/lampepfl/dotty/issues/1970

Case objects vs Enumerations in Scala - Stack Overflow

scala enumeration case-class
Rectangle 27 397

The example you have given only uses call-by-value, so I will give a new, simpler, example that shows the difference.

First, let's assume we have a function with a side-effect. This function prints something out and then returns an Int.

def something() = {
  println("calling something")
  1 // return value
}

Now we are going to define two function that accept Int arguments that are exactly the same except that one takes the argument in a call-by-value style (x: Int) and the other in a call-by-name style (x: => Int).

def callByValue(x: Int) = {
  println("x1=" + x)
  println("x2=" + x)
}

def callByName(x: => Int) = {
  println("x1=" + x)
  println("x2=" + x)
}

Now what happens when we call them with our side-effecting function?

scala> callByValue(something())
calling something
x1=1
x2=1

scala> callByName(something())
calling something
x1=1
calling something
x2=1

So you can see that in the call-by-value version, the side-effect of the passed-in function call (something()) only happened once. However, in the call-by-name version, the side-effect happened twice.

This is because call-by-value functions compute the passed-in expression's value before calling the function, thus the same value is accessed every time. However, call-by-name functions recompute the passed-in expression's value every time it is accessed.

I've always thought this terminology is needlessly confusing. A function can have multiple parameters which vary in their call-by-name vs call-by-value status. So it's not that a function is call-by-name or call-by-value, it's that each of its parameters may be pass-by-name or pass-by-value. Furthermore, "call-by-name" has nothing to do with names. => Int is a different type from Int; it's "function of no arguments that will generate an Int" vs just Int. Once you've got first-class functions you don't need to invent call-by-name terminology to describe this.

@Ben, that helps answer a couple questions, thanks. I wish more write-ups explained the semantics of pass-by-name this clearly.

@SelimOber If the text f(2) is compiled as an expression of type Int, the generated code calls f with argument 2 and the result is the value of the expression. If that same text is compiled as an expression of type => Int then the generated code uses a reference to some sort of "code block" as the value of the expression. Either way, a value of that type can be passed to a function expecting a parameter of that type. I'm pretty sure you can do this with variable assignment, with no parameter passing in sight. So what do names or calling have anything to do with it?

@Ben So if => Int is "function of no arguments that generates an Int", how it that different from () => Int? Scala seems to treat these differently, for instance => Int apparently doesn't work as the type of a val, only as the type of a parameter.

@TimGoodman You're right, it's a bit more complicated than I made out. => Int is a convenience, and it isn't implemented exactly as a function object is (presumably why you can't have variables of type => Int, though there's no fundamental reason why this couldn't work). () => Int is explicitly a function of no arguments that will return an Int, which needs to be called explicitly and can be passed as a function. => Int is sort of a "proxy Int", and the only thing you can do with it is call it (implicitly) to get the Int.

Call by name vs call by value in Scala, clarification needed - Stack O...

scala
Rectangle 27 19

The best way to do Scala is with IDEA and SBT. Set up an elementary SBT project (which it'll do for you, if you like) and run it in automatic compile mode (command ~compile) and when you save your project, SBT will recompile it.

You can also use the SBT plug-in for IDEA and attach an SBT action to each of your Run Configurations. The SBT plug-in also gives you an interactive SBT console within IDEA.

Either way (SBT running externally or SBT plug-in), SBT stays running and thus all the classes used in building your project get "warmed up" and JIT-ed and the start-up overhead is eliminated. Additionally, SBT compiles only source files that need it. It is by far the most efficient way to build Scala programs.

performance - Java compile speed vs Scala compile speed - Stack Overfl...

java performance scala compilation
Rectangle 27 249

1 :: 2 :: Nil // a list
list1 ::: list2  // concatenation of two lists

list match {
  case head :: tail => "non-empty"
  case Nil          => "empty"
}

Of course, Scala evolved other collections, in an ad-hoc manner. When 2.8 came out, the collections were redesigned for maximum code reuse and consistent API, so that you can use ++ to concatenate any two collections -- and even iterators. List, however, got to keep its original operators, aside from one or two which got deprecated.

So is it best practice to avoid ::: in favour of ++ now? Also use +: instead of ::?

:: is useful because of pattern matching (see Daniel second example). You cannot do that with +:

@Luigi If you are using List instead of Seq, you might as well use idiomatic List methods. On the other hand, it will make it harder to change to another type, if you ever desire to do so.

I find it good that one has both List idiomatic operations (like :: and :::) and more general operation that are common to other collections. I wouldn't drop either operation from the language.

:+
+:

Scala list concatenation, ::: vs ++ - Stack Overflow

list scala concatenation
Rectangle 27 32

With the present JVM Scala has an advantage on the account of being statically typed, as JVM support for dynamic typing -- reflection -- is slow. In fact, one Scala feature which must be implemented through the same techniques, structural types, is often warned against for this very reason.

Also, Scala accepts mutable objects just fine, and some algorithms are just faster to implement with mutability.

As both Scala and Java are essentially class-based languages, they interoperate more easily. Or, perhaps, more seamlessly. A Java class is a class to Scala, and a Scala class is a class to Java. Problems might arise when it comes to Scala's singletons or Java's static members, particularly when there's a framework involved expecting things to work in a certain way.

So I'd go with Scala on both these accounts. Clojure is, in many ways, a better language, and it certainly has very interesting features not present (so far) on Scala, but you reap such benefits by going fully functional. If you intend to do that, then Clojure is very likely better. If you don't, then you should probably stay with Scala.

The functional programming features of clojure are the most compelling reason why I am considering this language. I'm reaching the point where: if I'm not coding something in a functional fashion - why am I bothering with a scripting language embedded in Java anyway? I already have Python at my side for doing quick-and-dirty tasks.

Then go with Clojure.

"scripting language embedded in Java". Please justify.

@Daniel: Sorry for confusion. I meant the comment towards Ryan Delucchi. He says that Scala is a "scripting language embedded in Java", which I don't buy. (Unless he meant Clojure, which I have no idea about).

On Performance and Java Interoperability: Clojure vs. Scala - Stack Ov...

java performance scala clojure jvm