Skip to content

Scala for Java Refugees Part 1: main(String[])


This article is also available in Spanish and Bulgarian.

You know who you are.  You’re the developer who picked up Java years ago, maybe as a second language and better alternative to C++, maybe as your first language coming into the industry.  You’re comfortable with Java, you know its ins and outs, its moods.  It’s like an old girlfriend; you may not feel the vibe anymore, but you know just how to rub it so it smiles.  In short, you’re a craftsman, and Java is your workhorse tool.

You’re starting to to become a bit pragmatic about your language choice though.  To put it mildly, the Java honeymoon is over.  While you can hardly find enough fault with the language to just walk away, you’re certainly open-minded enough to consider alternatives.  You’ve heard of this new-fangled thing called Ruby – how could you not have heard, given the sheer noise level produced by its followers.  You’re impressed by the succinctness of its constructs and the power of its syntax, but you’re not sold on the idea of using a scripting language to build your enterprise app.  Dynamic typing and TextMate are all well and good, but for the real-world iron horse you’re going to need something with a bit more backbone.  As a good pragmatist, you stick with the tool that works: Java.

The good news is that there’s light at the end of the tunnel.  There’s a new language on the scene that’s taking the developer world by storm.  Scala seems to offer everything you’ve been looking for in a language: static typing, compiled to bytecode (so you can run it on all those ancient Java-capable servers), a succinct and expressive syntax.  You’ve seen a few examples which have really caught your eye.  It looks the spitting image of Java, except with half the useless constructs thrown out.  No semi-colons, no public static void method qualifiers; it even seems to have some sort of static type inference mechanism.

The only problem you have now is figuring out where to start.  You’ve tried looking on the Scala website, but what you found stopped you in your tracks.  Everything’s so…functional.  Lamdas, high-order functions, immutable state, recursion out the wazoo.  Suddenly things are looking less promising.

Have no fear, ye refugee of Java EE grid iron, all is not lost.  True, Scala is a functional language, but it’s also imperative and highly object oriented.  What does this mean?  It means that you don’t have to write code with the sole purpose of pleasing Haskell Curry.  You can write code that you can actually read a week from now.  You may even be able to show this code to your Java-loving coworkers and they just might understand it.  You don’t have to curry every function and avoid loops at all costs.  You can write your Java applications in Scala.  You just need the right introduction.


If you’re like me and can identify with the above, then this series is for you.  I’ve read a lot of articles and tutorials on Scala (Alex Blewitt’s series is highly recommended, especially if you’re interested in the more functional side of life), but few of these tutorials have even attempted to make things easier for the run-of-the-mill Java developer to make the transition.  I personally have very little FP (Functional Programming) experience, so I don’t think I could write an article about porting Scheme code to Scala even if I wanted to.  Instead, this series will focus on how Scala is just like Java, except better.

Did I mention Alex’s Scala introduction series?  Seriously, this is great reading, and not a bad introduction to Scala in and of itself.  Once you’re done reading my ramblings, you should run over and read some of his more coherent stuff.   The more the merrier!

Getting Started

object HelloWorld extends Application {
  println("Hello, World!")

Nothing like getting things rolling with a little code.  Notice the refreshing lack of mandatory semicolons.  We can use them anyway, but they aren’t required unless we need multiple statements on a single line.  This code sample does exactly what it looks like, it defines an application which (when run using the scala interpreter) will print “Hello, World!” to stdout.  If you put this code into a file with a .scala extension, you can then compile it using the scalac compiler.  The result will be a single .class file.  You could technically run the .class using the java interpreter, but you would have to mess with the classpath a bit.  The easiest thing to do is just use the scala command like so:

scalac hello.scala
scala HelloWorld

Notice the name of the file in question?  Unlike Java, Scala doesn’t force you to define all public classes individually in files of the same name.  Scala actually lets you define as many classes as you want per file (think C++ or Ruby).  It’s still good practice to follow the Java naming convention though, so being good programmers we’ll save our HelloWorld example in a file called “HelloWorld.scala”.


Just a brief note on your first few moments with Scala: using the right editor is key.  As you must have learned from your many years in the Java world, IDEs are your friend.  Scala, being a much younger language doesn’t have very good IDE support yet.  It is a static, general purpose language like Java, so IDE support will be forthcoming.  For the moment however, you’re stuck with a very limited set of options.

  • Eclipse (using one of two shoddy and unstable Scala plugins)
  • Emacs
  • IntelliJ (basically just syntax highlighting support)
  • TextMate
  • VIM
  • jEdit

There are a few other options available, but these are the biggies (to see a full list, look in the misc/scala-tool-support/ directory under the Scala installation root).  My personal recommendation is that you use jEdit or TextMate, though if you’re feeling adventurous you’re free to try one of the Eclipse plugins too.  Scala support in Eclipse has the advantage (at least with the beta plugin) of features like semantic highlighting, code completion (of both Scala and imported Java classes) and other IDE-like features.  In my experience though, both Eclipse plugins were unstable to the point of unusable and as such, not worth the trouble.  Scala is a much cleaner language than Java, so it really does have less of a need for a super powerful IDE.  It would be nice, no question about that, but not essential.

More Hello World

object HelloWorld2 {
  def main(args:Array[String]) = {
    var greeting = ""
    for (i <- 0 until args.length) {
      greeting += (args(i) + " ")
    if (args.length > 0) greeting = greeting.substring(0, greeting.length - 1)

Save this in a new file (we’ll call it “HelloWorld2.scala”), compile and run using the following commands:

scalac HelloWorld2.scala
scala HelloWorld2 Hello, World!

Once again, this prints “Hello, World!” to stdout.  This time we did things a little differently though.  Now we’ve got command line arguments coming into our app.  We define a variable of type String, iterate over an array and then call a bit of string manipulation.  Fairly straightforward, but definitely more complex than the first example.  (Note: Scala mavens will no doubt suggest the use of Array#deepMkString(String) (similar to Ruby’s Array::join method) instead of iterating over the array.  This is the correct approach, but I wanted to illustrate a bit more of the language than just an obscure API feature).

The first thing to notice about this example is that we actually define a main method.  In the first example, we just extended Application and declared everything in the default constructor.  This is nice and succinct, but it has two problems.  First, we can’t parse command line args that way.  Second, such examples are extremely confusing to Scala newbies since it looks more than slightly magical.  Don’t worry, I’ll explain the magic behind our first example in time, but for now just take it on faith.

In the example, we define a main method that looks something like our old Java friend, public static void main.  In fact, this is almost exactly the Scala analog of just that method signature in Java.  With this in mind, an experienced developer will be able to pick out a few things about the language just by inspection.

First off, it looks like all methods are implicitly public.  This is somewhat correct.  Scala methods are public by default, which means there’s no public method modifier (private and protected are both defined).  It also looks like Scala methods are static by default.  This however, is not entirely correct.

Scala doesn’t really have statics.  The sooner you recognize that, the easier the language will be for you.  Instead, it has a special syntax which allows you to easily define and use singleton classes (that’s what object means).  What we’ve really declared is a singleton class with an instance method, main.  I’ll cover this in more detail later, but for now just think of object as a class with only static members.

Upon deeper inspection of our sample, we gain a bit of insight into both Scala array syntax, as well as an idea of how one can explicitly specify variable types.  Specifically, let’s focus on the method declaration line.

def main(args:Array[String]) = {

In this case, args is a method parameter of type Array[String].  That is to say, args is a string array.  In Scala, Array is actually a class (a real class, not like Java arrays) that takes a type parameter defining the type of its elements.  The equivalent Java syntax (assuming Java had an Array class) would be something like this:

public static void main(Array<String> args) {

In Scala, variable type is specified using the variable:Type syntax.  Thus, if I wanted to declare a variable that was explicitly of type Int, it would be done like this:

var myInteger:Int

If you look at the sample, we actually do declare a variable of type String.  However, we don’t explicitly specify any type.  This is because we’re taking advantage of Scala’s type inference mechanism.  These two statements are semanticly equivalent:

var greeting = ""

var greeting:String = ""

In the first declaration, it’s obvious to us that greeting is a String, thus the compiler is able to infer it for us.  Both greetings are staticly type checked, the second one is just 7 characters shorter.  :-)

Observant coders will also notice that we haven’t declared a return type for our main method.  That’s because Scala can infer this for us as well.  If we really did want to say something explicitly, we could declare things like this:

def main(args:Array[String]):Unit = {

Once again, the type antecedes the element, delimited by a colon.  As an aside, Unit is the Scala type for I-really-don’t-care-what-I-return situations.  Think of it like Java’s Object and void types rolled into one.

Iterating Over an Array

var greeting = ""
for (i <- 0 until args.length) {
  greeting += (args(i) + " ")

By the way, it’s worth noting at this juncture that the convention for Scala indentation is in fact two spaces, rather than the tabs or the four space convention that’s so common in Java.  Indentation isn’t significant, so you can really do things however you want, but the other four billion, nine hundred, ninety-nine million, nine hundred, ninety-nine thousand, nine hundred and ninety-nine people in the world use the two space convention, so it’s probably worth getting used to it.  The logic behind the convention is that deeply nested structure isn’t a bad sign in Scala like it is in Java, thus the indentation can be more subtle.

This sample of code is a bit less intuitively obvious than the ones we’ve previously examined.  We start out by declaring a variable, greeting of inferred type String.  No hardship there.  The second line is using the rarely-seen Scala for loop, a little more type inference, method invocation on a “primitive” literal and a Range instance.  Developers with Ruby experience will probably recognize this equivalent syntax:

for i in 0..(args.size - 1)
  greeting += args[i] + " "

The crux of the Scala for loop is the Range instance created in the RichInt#until method.  We can break this syntax into separate statements like so:

val range = 0.until(args.length)
for (i <- range) {

Oh, that’s not a typo there declaring range using val instead of var.  Using val, we’re declaring a variable range as a constant (in the Java sense, not like C/C++ const).  Think of it like a shorter form of Java’s final modifier.

Scala makes it possible to invoke methods using several different syntaxes.  In this case, we’re seeing the value methodName param syntax, which is literally equivalent to the value.methodName(param) syntax.  Another important action which is taking place here is the implicit conversion of an Int literal (0) to an instance of scala.runtime.RichInt.  How this takes place isn’t important right now, only that RichInt is actually the class declaring the until method, which returns an instance of Range.

Once we have our Range instance (regardless of how it is created), we pass the value into the magic for syntax.  In the for loop declaration, we’re defining a new variable i of inferred type Int.  This variable contains the current value as we walk through the range [0, args.length) - including the lower bound but not the upper.

In short, the for loop given is almost, but not quite equivalent to the following bit of Java:

for (int i = 0; i < args.length; i++) {

Obviously the Java syntax is explicitly defining the range tests, rather than using some sort of Range object, but the point remains.  Fortunately, you almost never have to use this loop syntax in Scala, as we'll see in a bit.

The body of the loop is the one final bit of interesting code in our sample.  Obviously we're appending a value to our greeting String.  What I'm sure struck you funny (I know it did me) is the fact that Scala array access is done with parentheses, not square brackets.  I suppose this makes some sense since Scala type parameters are specified using square brackets (rather than greater-than/less-than symbols), but it still looks a little odd.

To summarize, the upper sample in Scala is logically equivalent to the lower sample in Java:

var greeting = ""
for (i <- 0 until args.length) {
  greeting += (args(i) + " ")

String greeting = "";
for (int i = 0; i < args.length; i++) {
    greeting += args[i] + " ";

A Better Way to Iterate

In Java 5, we saw the introduction of the so-called for/each iterator syntax.  Thus, in Java we can do something like this:

for (String arg : args) {
    greeting += arg + " ";

Much more concise.  Scala has a similar syntax defined as a high-order function - a function which takes another function as a parameter.  I'll touch on these more later, but for the moment you can take it as more magic fairie dust:

args.foreach { arg =>
  greeting += (arg + " ")

Here we see that foreach is a method of class Array that takes a closure (anonymous function) as a parameter.  The foreach method then calls that closure once for each element, passing the element as a parameter to the closure (arg).  The arg parameter has an inferred type of String because we're iterating over an array of strings.

Now as we saw earlier, Scala methods can be called in different ways.  In this case we're calling foreach omitting the parentheses for clarity.  We also could have written the sample like this:

args.foreach(arg => {
  greeting += (arg + " ")

Scala actually defines an even more concise way to define single-line closures.  We can omit the curly-braces altogether by moving the instruction into the method invocation:

args.foreach(arg => greeting += (arg + " "))

Not bad!  So our fully rewritten sample looks like this:

object HelloWorld2 {
  def main(args:Array[String]) = {
    var greeting = ""
    args.foreach(arg => greeting += (arg + " "))
    if (args.length > 0) greeting = greeting.substring(0, greeting.length - 1)

The syntax looks great, but what is it actually doing?  I don't know about you, but I hate having to use APIs that I don't know how to replicate myself.  With a bit of work, we can recreate the gist of the Scala foreach method in pure Java.  Let's assume for a moment that Java had an Array class.  In that Array class, let's pretend there was a foreach method which took a single instance as a parameter.  Defined in code, it might look like this:

public interface Callback<T> {
    public void operate(T element);
public class Array<T> {
    // ...
    public void foreach(Callback<T> callback) {
        for (T e : contents) {   // our data structure is called "contents"

I could have defined foreach recursively (as it is defined in Scala), but remember I'm trying to keep these explanations clear of the tangled morass that is FP.  :-)

Sticking with our goal to see an analog to the Scala foreach, here's how we would use the above API in Java:

public class HelloWorld2 {
    public static void main(Array<String> args) {
        final StringBuilder greeting = new StringBuilder();
        args.foreach(new Callback<String>() {
            public void operate(String element) {
                greeting.append(element).append(' ');
        if (args.length() > 0) {
            greeting.setLength(greeting.length() - 1);

Starting to see why Scala is legitimately appealing?  If you're like me, you just want Scala to be a more concise Java.  In this case, that's exactly what we've got.  No strange functional cruft, no immutable state.  Just solid, hard-working code.

A Word About Built-in Types

Because Scala is built on the JVM, it inherits a lot of its core API directly from Java.  This means you can interact with Java APIs.  More than that, it means that any code you write in Scala is using Java APIs and functions.  For example, our sample HelloWorld2 is using a string variable greeting.  This variable is literally of type java.lang.String.  When you declare an integer variable (type Int) the compiler converts this to the Java primitive type int.

It's also worth noting that there are a number of built-in implicit conversions (just like the Int to RichInt we saw earlier with the Range creation).  For example, Scala's Array[String] will be implicitly converted to a Java String[] when passed to a method which accepts such values.  Even Scala type parameters are available and interoperable with Java generics (in the current development version of Scala and slated for inclusion in 2.6.2).  In short, when you use Scala you’re really using Java, just with a different syntax.


Scala doesn’t have to be complex, needlessly academic or require a master’s degree in CompSci.  Scala can be the language for the common man, the 9-5 developer who’s working on that next enterprise web application.  It has real potential to provide the clear syntax Java never had without forsaking the power and stability of a trusted, first-class language.  Convinced?

Up next, classes, methods and properties: everything you need to know to get rolling with object-oriented programming in Scala.


  1. Nice Daniel :) I look forward to the next issue :)

    Tim Yates Monday, January 7, 2008 at 2:22 am
  2. This kind of article is exactly what Scala adoption needs: not a demonstration of how Scala introduces the best of function purity and meta-programming to achieve uber-modularity and concurrency, but how it enables small applications already writeable in Java to be written more simply, more understandably and easier maintainably.

    René Ghosh Monday, January 7, 2008 at 3:07 am
  3. Hi,
    Very interesting tutorial.

    builder.append(element).append(‘ ‘);
    be (I think):
    greeting.append(element).append(‘ ‘);

    “Here we see that foreach is a method of class Array that takes a closure (anonymous function) as a parameter. ”
    Don’t you mean a lambda instead of a closure? (Not sure myself.)

    About the part “Even Scala type parameters are available and interoperable with Java generics (in the current development version of Scala).”: maybe it’s worth it to mention this will be added in 2.6.2, for those who read this tutorial later.

    The automatic conversion of Int to RichInt is interesting, I’m wondering how far this goes. Does it also detect when an Int should in fact be a Long? E.g. say you have “var n = 5″ this could be of type Byte (if there’s such a thing). A bit later you do “n = 3000000000″. Will it detect that “n” should in fact be a Long?

    I’m looking forward to your next post on this subject.


    LudoA Monday, January 7, 2008 at 3:46 am
  4. Excellent article!

    I would also suggest the following as a closer parallel to Java’s for/each syntax:

    for (arg

    Jorge Monday, January 7, 2008 at 3:52 am
  5. Excellent article!

    I would also suggest the following as a closer parallel to Java’s for/each syntax:

    for (arg <- args) {
    greeting += arg + " "

    Jorge Monday, January 7, 2008 at 3:54 am
  6. Hi Daniel,
    that’s a nice article. I really recognized myself in the first paragraphs. I wouldn’t describe myself as a Java refugee, however, and I remain unconvinced that Scala is the thing I should use for my next projects.
    Part of the reason is the lack of a good Eclipse plugin. It should be possible to write an Eclipse plugin in Scala itself. Not only would that serve as an excellent example and reference material but it would also show me that a problem I consider non-trivial in Java can be done easier in Scala – surely somebody from the Scala community should be able to take that on. I mean, show me the hard stuff. Some syntactic sugar and a little less text isn’t quite enough to convert me; I believe that the relative merits of conciseness diminish if your codebase size becomes bigger, and I don’t mind the boilerplate code so much as long as I have sophisticated code inspection (e.g., “search references”) and templating and refactoring tools.
    Anyhow, I’m looking forward to the sequel to this article.
    Regards, Leo

    Leo Monday, January 7, 2008 at 6:53 am
  7. Very good! I look forward to the other parts.

    Robert Monday, January 7, 2008 at 8:13 am
  8. I realise you are trying to show how Scala can be written without complex functional constructs, but folds are really, really useful for joining lists together.

    For instance, you could rewrite your example as:

    val greeting = args.reduceLeft((output, arg) => output + ” ” + arg)


    val greeting = args.reduceLeft( _ + ” ” + _)

    And if you really wanted to shamelessly cheat, then you could just use the “mkString” method:

    println(args.mkString(” “))

    James Reeves Monday, January 7, 2008 at 8:55 am
  9. @James
    Yes, using folds or (easier still) mkString would definitely be the easiest way to go. I don’t know if you’ve seen it though, but the (_ + _) expression has become the canonical example of how Scala is *not* clear or expressive. :-) Obviously it makes perfect logical sense, but if you’re not expecting to have to think functionally, it kinda catches you off-guard and really turns you off to the whole language.

    Yeah, I thought about using the for comprehension syntax, but decided against it. I don’t know what best practice in Scala is, but in other languages which support similar functionality (like Ruby), best practice is to iterate by passing a closure to the iterable object. Semantically, it’s almost exactly equivalent to a for comprehension, but I sort-of like the syntax better.

    Good catch on the builder vs greeting! I habitually use “builder” as the variable name for my trivial StringBuilder objects. Some coding habits are hard to break… :-)

    Yes, lambda would also be an acceptable way to refer to the construct. Actually I think the proper term in Scala would be “anonymous function”. I prefer the term “closure” since it seems to unify the meanings across different languages (unifying Ruby procs, Java 7 “closures”, Haskell lamdas, etc). Also, the term “lambda” implies (at least to me) a more discrete, lazily evaluated expression. When I think of a “closure”, I almost always think of something with a bit more substance.

    Implicit conversions are about the second coolest thing in the entire Scala language. In one fell swoop they solve the problems of primitives vs autoboxed wrappers, class extensions, and even some type theory issues in duck typing. They’re on my list of things to cover, though not in the first few articles (coming from a Java background, they do seem a bit odd).

    Daniel Spiewak Monday, January 7, 2008 at 9:42 am
  10. The simple “scala Hello” didn’t work for me – I did have to specify the classpath (-cp .) just as in Java – a trivial but nonzero “messing with the classpath” step.

    Joel Klein Monday, January 7, 2008 at 9:54 am
  11. Hmm, that’s interesting because I just tried the example on my machine (Vista, Java 6, Scala 2.6.0) and it worked just fine without -cp . What OS, Java and Scala version are you running?

    Daniel Spiewak Monday, January 7, 2008 at 10:12 am
  12. > What OS, Java and Scala version are you running?

    XP Pro SP2, Java 1.4, Scala 2.6.1. I tried Scala 2.6.0 with that combo, and also just tried using Java 1.5 and 1.6 and got the same result. I’m assuming adding the JDK bin to the front of the path and setting JAVA_HOME are sufficient to point Scala to the right Java. Actually, scala.bat and scalac.bat seem to just take whatever “java” is on the path, so setting the path correctly should be enough configuration. So, not sure what’s up.

    Anyway, it’s a trivial thing in a nice writeup. It got me actually trying some Scala code more than the official tutorials did, so thanks!

    Joel Klein Monday, January 7, 2008 at 11:00 am
  13. > So, not sure what’s up.

    Found the problem — I had *something* on my %CLASSPATH%.

    The scalac man page (referred to by the scala man page regarding options like classpath) say that “.” is the default classpath, but you can override that by specifying something via the CLASSPATH variable.

    So, the caveat to the simple example would be to make sure CLASSPATH is not set, or include “.” manually.

    Joel Klein Monday, January 7, 2008 at 11:06 am
  14. Nice tip, Joel. Thanks for investigating!

    Daniel Spiewak Monday, January 7, 2008 at 11:13 am
  15. Thanks for the metaphor with the old girl-friend. I had three weeks off where I hacked Scala and thought Scala. Today the first day back to work and I thought: What the heck is that? (Java) – it took me a while to come down to earth again.

    Now I am pretty sure that there is no point to take up again with my (real-life) old girl-friend. The feeling was exactly the same.

    Yes, I know this sounds bizarre

    Carsten Monday, January 7, 2008 at 3:49 pm
  16. Throughout the article, the line
    greeting += args(i) + ” ”
    is not doing what you think it is. Because of the operator precedence, this is parenthesized as
    (greeting += args(i)) + ” ”
    with the result that the space is lost.

    There is a bug report in on this ( In the meantime, it’s probably a good idea to use parentheses when using an op= assignment operator in Scala:
    greeting += (args(i) + “”)

    Doug Pardee Thursday, January 10, 2008 at 4:50 pm
  17. Nice catch! I just confirmed this in scala interactive mode. Updating the article so that it is correct.

    Daniel Spiewak Thursday, January 10, 2008 at 5:39 pm
  18. @Leo

    The Eclipse plugin for scala is actually written in Scala. Personally, I think this is a weakness. I tried to get it running a while ago, to see whether there might be something I could fix, but it was too painful (for me at least) to get it running. If it were instead written in Java, it would be seamlessly supported by Eclipse.

    Eelco Hillenius Saturday, January 12, 2008 at 11:09 pm
  19. // @LudoA
    object Test {
    val n = 3000000000;
    def main(args:Array[String]) {

    $ ./build/quick/bin/scalac -d /tmp test/pending/detectLong.scala
    test/pending/detectLong.scala:2: error: integer number too large
    val n = 3000000000;
    one error found

    remedy: write val n = 3000000000L; // note the ‘L’ suffix

    If you explicitly mark the thing as long, then the type of the value will be inferred as long, with implications for the rest of the program. Fortunately, thanks to static type checking, those implications are somewhat under control.

    buraq Sunday, January 13, 2008 at 10:11 am
  20. I don’t know why you put down FP repeatedly :

    ” the tangled morass that is FP”
    “No strange functional cruft, no immutable state. Just solid, hard-working code.”

    Don’t you see that Scala is Java + FP ?
    In the words of M. Odersky : “the programming language Scala [which] tries to achieve a fusion of object-oriented and functional programming”

    APL Wednesday, January 16, 2008 at 9:32 am
  21. Oh Scala is Java + FP, no doubt about that. But Functional Programming can be extremely confusing for those with a background exclusively in the imperative paradigm.

    Daniel Spiewak Wednesday, January 16, 2008 at 10:35 am
  22. Good !
    Starting with the compiler and full objects is better for Java heads (like me), not that expression stuff for scripters …

    A coupe of comments:
    greeting.length – 2 => greeting.length – 1 (at least in 2.6.1) Maybe, this bug was left from the priority thing with +=

    “Scala array access is done with parentheses, not square brackets. I suppose this makes some sense since Scala type parameters are specified using square brackets (rather than greater-than/less-than symbols), but it still looks a little odd.”
    => talk about Uniform access (if greeting changes to another type, greeting.apply(i) will still work, also this in an object, not a special syntax like in Java for arrays).

    javier Wednesday, January 16, 2008 at 3:34 pm
  23. Actually, the (greeting.length – 2) thing is to strip off the trailing space. This would be uniform across Scala versions since the length() method is actually implemented in Java’s String class.

    Daniel Spiewak Wednesday, January 16, 2008 at 3:39 pm
  24. scala> var hello= “Hi you ”
    hello: java.lang.String = Hi you

    scala> println(“#” + hello.substring(0,hello.length -2) + “#”)
    #Hi yo#

    javier Thursday, January 17, 2008 at 5:41 am
  25. public String substring(int beginIndex,
    int endIndex)
    Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex – 1.

    You wrote it ok in the Java code (check it), but you contradict yourself => The interval is open at the right : [0, indexnotincluded).

    javier Thursday, January 17, 2008 at 5:45 am
  26. Yeah, you’re right, javier. Have I mentioned that I hate String processing in Java? :-)

    Updating the article…

    Daniel Spiewak Thursday, January 17, 2008 at 9:57 am
  27. Brilliant! Keep it coming!

    David Linsin Sunday, February 3, 2008 at 12:02 pm
  28. Thank you for the series, I’m not so tired of Java as open to new ideas, but the truth is that as you say, the documentation I could find on Scala simply put me off and I decided to wait until something more “friendly” was written. And here it comes! :)

    My only two “but” would be that making the Scala sentences one-liners do not make them more elegant, but less clear for me, but that’s a matter of taste. And that you seem to have made the Java equivalent explictely ugly and that makes it a bit “unreal”. No sane person would actually use that construct to iterate over an String array and concatenate the results, and even though I understand you are trying to explain that there’s more in the Scala version and getting the same in Java would mean going beyond ugliness, I think showing a “real” equivalent, even though less powerful, would keep with the tone of the article.

    Nice series, though. Thank your for writing it :)

    Daniel Tuesday, February 5, 2008 at 2:16 am
  29. I agree, Daniel. No sane Java developer would ever write code like I have done. The reason I did it like that was to demonstrate the “magic” behind the foreach method.

    Daniel Spiewak Tuesday, February 5, 2008 at 8:33 am
  30. Hello,

    I am a senior PHP developer (who let a PHP “developer” in here??), zealot follower of the Design Patterns paradigm who has grown tired of PHP’s inability to scale. Ironically, I was able to read your first two paragraphs, minus the last two sentences, s/Java/PHP’ed and absolutely relate!

    I have been looking sideways at Java for some time now but with my work primarily focused on the web, where PHP still dominates over JSP, I was not sure that simply switching to Java is a viable option. Furthermore I am now on the verge of starting something and am looking into various options for what platform to use, as I hope to not use PHP. My searches brought me here.

    I just wanted to thank you for this very helpful article, before moving on to your next chapter. And share with you the notion that it makes Scala very appealing to at least one non-Java developer. So – Thanks. :-)

    Post-O-Matic Sunday, February 24, 2008 at 4:07 am
  31. If you’re looking at the web arena, I would give careful consideration to using Wicket with Scala. All of the power and scalability of a really first-class Java web framework coupled with the concise and expressive syntax of Scala.

    Daniel Spiewak Sunday, February 24, 2008 at 12:07 pm
  32. IntelliJ has improved their Scala support. Does more than just basic syntax highlighting.

    The plugin is here:

    List of features:

    Roopinder Thursday, April 23, 2009 at 6:00 am
  33. This is one awesome article -
    I have printed it out just so that I can really follow it and annotate the code with pen as I read along. In fact, I have been thinking about learning a JVM based language, and this seems to fit what I need.

    Played with Groovy a bit, but this seems to be the future. My initial problem with Scala was the Eclipse Plug in, but that has now been sorted.

    Cheers for sharing :)

    Evans Friday, August 14, 2009 at 3:17 am
  34. Great article, but I have some nits to pick:

    > I prefer the term “closure”

    Closures are not the same as anonymous functions (lambdas). I agree it’s a nicer term, and I prefer to use it too, because it sounds more erudite, but I think it’s important to pick words according to what they actually mean, rather than what we’d like them to mean.

    Also, “antecede” is not an antonym of “precede”, it’s a synonym.

    Klortho Tuesday, August 18, 2009 at 7:29 pm
  35. I, too, like most programmer grunts, I suppose, came to functional programming from the iterative world, although I did study lisp in school. But I’ve found that FP has really grown on me the more that I’ve been exposed to it. So much so that I can’t help but cringe now when I see these kinds of iterative loops, especially when the FP equivalents are so elegant and clean. So, I’d like to offer up that this is the *right* way to code the example you give in this article:

    val argsString = => “‘” + s + “‘”).mkString(“, “)
    println(“Arguments: ” + argsString)

    It might be cryptic on first glance, to someone unfamiliar with Scala, but I think it’s really worth it to understand how to do it this way, and why it’s better in general.


    Klortho Tuesday, August 18, 2009 at 8:05 pm
  36. > Scala makes it possible to invoke methods using several different syntaxes.

    How clever is this? From a concise language I would expect a minimal reduction to avoid comments about so many confusing syntax alternatives found here.

    gerbre Saturday, September 5, 2009 at 10:30 am
  37. We have both a Scala / Java environment in our office. The scala developers are very “ivory tower”. They manage their projects with vim, they sit around discussing byte code all day, but in general are good developers. Problem is, for all the efficiencies that Scala apparently brings, they are months, even a year+ late on major projects. Yet, the Java people are consistently on time. The biggest reason I think is the editor. The scala guys, take weeks or months to do a simple refactor, something it takes the Java guys minutes to do with eclipse.

    Until the tools are there, Scala will have a tough time kicking Java out if the #1 spot for most deployed language in the world. I’d expect that unless Scala is acquired by SpringSource, its probably going to end up like Ruby. A quick climax and then a fast fall.

    Zillo Saturday, January 23, 2010 at 11:58 am
  38. Very Nice introduction… I like it very much. Will send this link to my friends as well :-)

    Senthil Monday, April 5, 2010 at 12:24 am
  39. It looks very interesting I must admit but I still have some doubts:

    Consider this code

    args.foreach { arg =>
    greeting += (arg + ” “)

    instead of

    foreach (String arg : args) {
    greeting += arg + ” “;

    isn’t the structure of the code more difficult to recognize when the foreach is not at the beginning of the line? The 2-space indentation also adds to this feeling. The structure can’t be seen so quickly. And it gets even worse with the single-instruction closure:

    args.foreach(arg => greeting += (arg + ” “))

    It’s much more difficult to see the loop in a function containing this line. But I think that’s very important since the number of (possibly nested) for loops reflects more or less directly the runtime performance of your code.

    Also I’m struggling with the fact, that things can be done in so much different ways. For example, you say one can still use the semicolons. Then everybody can do what he wants in this regard. I think it’s highly desirable to have a language where things can only be done in one way because that forces everyone to do it exactly the same way. This reduces the sum of different syntax tricks I have to master in order to understand the language. It’s also better if in a project team the source code always looks exactly the same way regardless of who has written it.

    So, while I think there are really refreshing concepts here, I wouldn’t be so sure if I would want to change to Scala only because it’s supposed to be a “better” Java. There are also some studies that show, that programmers spent the fewest time with typing in code. So you can’t really save so much time with fewer syntax. But you will loose a lot of time if the syntax is harder to understand …

    Alex Friday, June 18, 2010 at 2:00 pm
  40. At the risk of opening a can of worms… why does anybody think that spaces are better than tabs? I fail to see it; tabs allow everybody to pick their own indentation size without having a mess of different indentations when code is edited by more than one programmer (provided of course that everyone is using a modern editor that can support different tab sizes; I don’t know of an editor that doesn’t). If I want to have 8 spaces, why can’t I? What if I really, really, want 6 spaces? I can’t when people use spaces instead of tabs. It’s like trying to force all editors to show scala keywords in a certain color.

    Yes, I’m somewhat upset… and this is kind of ranting, but really… please… for the love of everything sane and beautiful, just use tabs.

    alan Tuesday, June 22, 2010 at 5:34 pm
  41. @alan

    If you try to line up parameters, for example, a different tab size will screw up the formatting. By using TABs you force everyone to have the same tab size unless you never, never try to do any fancy formatting

    See this example:

    void funct(T1 par1,
    TAB TAB T2 par2,
    TAB TAB T3 par3) {
    TAB body; TAB TAB TAB // coment

    The code above will look fine in any editor if indented with spaces. If you indent it with tabs, you will have to use TABs with size 4 to make T1 and T2 line up (and if the function name changes, you will have to mix tabs and spaces). Same thing with the inline “//coment”, if you want to line it up with other comments, tabs won’t do.

    marcus Thursday, July 29, 2010 at 11:57 am
  42. Wow what an excellent start to the article: “It’s like an old girlfriend; you may not feel the vibe anymore, but you know just how to rub it so it smiles. In short, you’re a craftsman, and Java is your workhorse tool.”

    The first sentence is pretty striaghtforward, but chaining that with the latter, does he compare a girlfriend to a workhorse? Please don’t misinterpret me, this is not some feministic disagreement with the writer, instead I would give kudos to him for being so brave :)

    Also the rest of the article (series) is great.

    Johnny M Tuesday, October 12, 2010 at 10:12 pm
  43. Its a really nice article … thanks a lot !!

    vimal Wednesday, October 13, 2010 at 5:31 am
  44. Hello Daniel,

    Thanks for this article, awesome work :-)

    Just one hint about an outdated subject:

    Since Scala 2.9.0
    object HelloWorld extends App // rather than Application
    did became idiomatic to define a simple application.

    Lumiha Wednesday, September 14, 2011 at 8:37 am
  45. seems interesting…… but when Scala becomes popular (hopefully) in the future, wouldn’t it be facing legal objections from Oracle for using Java as its base like the way android is facing lawsuits from oracle right now?

    Syed Rakib Al Hasan Wednesday, September 21, 2011 at 8:24 am
  46. @Syed

    I don’t think so. As far as I know, the reason for the lawsuit is that Android has its own versions of the JVM and JDK w/o permission from Oracle. Scala, however, uses functionality that was purposefully built into the JVM to allow another language to be interpreted/compiled by the JVM. i.e. Scala is sort of like a special library for Java, while Android is a type of clone of Java.

    Dexter Wednesday, March 21, 2012 at 12:25 pm

Post a Comment

Comments are automatically formatted. Markup are either stripped or will cause large blocks of text to be eaten, depending on the phase of the moon. Code snippets should be wrapped in <pre>...</pre> tags. Indentation within pre tags will be preserved, and most instances of "<" and ">" will work without a problem.

Please note that first-time commenters are moderated, so don't panic if your comment doesn't appear immediately.