Article Discussion
First Steps to Scala
Summary: In this article, you'll follow twelve steps that are designed to help you understand and gain some basic skills in the Scala programming language.
32 posts.
The ability to add new comments in this discussion is temporarily disabled.
Most recent reply: May 6, 2010 3:54 PM by Venki
    Admin
     
    Posts: 15 / Nickname: admin / Registered: January 17, 2002 3:57 PM
    First Steps to Scala
    May 11, 2007 8:23 PM      
    In this article, you'll follow twelve steps that are designed to help you understand and gain some basic skills in the Scala programming language.

    http://www.artima.com/scalazine/articles/steps.html

    What do you think of Scala?
    • Stanislas
       
      Posts: 2 / Nickname: graven / Registered: May 3, 2007 8:09 PM
      Re: First Steps to Scala
      May 12, 2007 2:05 AM      
      Personnaly, I like Scala, it looks like a very cute development effort. But I have to admit that hybrid languages aren't likely to have any future — they lack lazyness that is vital to the success of functional language.
      • Morel
         
        Posts: 1 / Nickname: masklinn / Registered: September 11, 2005 7:44 AM
        Re: First Steps to Scala
        May 12, 2007 11:12 AM      
        > Personnaly, I like Scala, it looks like a very cute
        > development effort. But I have to admit that hybrid
        > languages aren't likely to have any future — they lack
        > lazyness that is vital to the success of functional
        > language.

        I fail to see how lazyness (as a core semantic of the language) is "vital" to functional language. Only one lazy functional language is even remotely widespread (Haskell, Miranda is also lazy but one can't say it's "widespread"), the vast majority of functional languages follow a strict evaluation model (pretty much every Lisp dialects, pretty much every ML dialects and derivatives including SML and OCaml, Erlang, ...) with the potential ability to include local lazyness (Scheme, D, Nemerle).

        Not to mention that lazy evaluation still has huge execution-time and memory behaviour issues (which lead to the introduction of strict-evaluation operators and variants in Haskell for optimization purposes...)
    • Tomi
       
      Posts: 1 / Nickname: tmaila / Registered: May 13, 2007 7:49 PM
      Re: First Steps to Scala
      May 14, 2007 0:51 AM      
      Nice article guys! It's really nice to see Scala being introduced in this extent here at artima! Keep up with the good work.
    • James
       
      Posts: 128 / Nickname: watson / Registered: September 7, 2005 3:37 AM
      Re: First Steps to Scala
      May 14, 2007 5:08 AM      
      This is really a great intro. I wish I had this when I was first trying to figure things out (not that I've figured it all out.)

      Keep up the good work and thanks.
    • Ravi
       
      Posts: 2 / Nickname: ravim / Registered: January 27, 2003 7:14 PM
      Re: First Steps to Scala
      May 15, 2007 5:49 AM      
      I find I need to say Console.println("Hello") vs println("hello") as described in the article.

      scala> println("j")
      <console>:4: error: not found: value println
      val line3 = println("j")



      What am I doing wrong?
      • Ravi
         
        Posts: 2 / Nickname: ravim / Registered: January 27, 2003 7:14 PM
        Re: First Steps to Scala
        May 15, 2007 6:13 AM      
        Urgh it seems I had the wrong version. Scala 2.5RC doe sindeed have the "println" construct.

        It would be nice if the scala interpreter could output the version number.

        something like ...

        $python
        Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25)
        [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
        Type "help", "copyright", "credits" or "license" for more information.
        >>>
        • Lex
           
          Posts: 3 / Nickname: lexspoon / Registered: October 9, 2006 11:13 PM
          Re: First Steps to Scala
          May 15, 2007 11:58 PM      
          All the Scala tools accept -version. Since you usually should not care about the version so much, I am going to leave out the Pythonic display of the version at every invocation.

          $scala -version
          Scala code runner version 2.5.0 -- (c) 2002-2007 LAMP/EPFL
    • Mark
       
      Posts: 2 / Nickname: puzzler / Registered: June 9, 2006 11:07 AM
      Re: First Steps to Scala
      May 14, 2007 7:48 PM      
      Good, lucid introduction overall. I still don't understand the order in which Scala calls the various overridden methods it inherits from its traits and superclass. I can't extrapolate from the exclamatorygreeter mixin example to understand how the chain would be resolved in general. Care to elucidate?
      • Lex
         
        Posts: 3 / Nickname: lexspoon / Registered: October 9, 2006 11:13 PM
        Re: First Steps to Scala
        May 16, 2007 0:16 AM      
        The details are in the spec.

        http://www.scala-lang.org/docu/files/ScalaReference.pdf

        By the way, this spec is readable as specs go. There is a ton of detail, but it is meant to be readable, not to be leverage for lawyers.

        Anyway, the rule is that inherited classes and mixed in traits get linearized. Message sends invoke the first class/trait in the linearization that has a matching method, and super calls work their way up through the linearization. The precise linearization algorithm is in the spec, but it is an intuitive one IMHO.

        Note that with this rule, you can evaluate all of the methods by simply chaining "super" calls. If the first method invokes "super", and so do all the others except for the last, then you will end up invoking each method one time. This pattern is practically impossible with multiple inheritance, and is awkward with the original traits from U. Berne.
    • Justin
       
      Posts: 1 / Nickname: jufo / Registered: May 28, 2007 3:30 AM
      Re: First Steps to Scala
      May 28, 2007 10:08 AM      
      I found the article really useful, and timely.

      While the examples based on printing program arguments clearly need to be run as scripts, everything else can be run interactively in the interpreter. This takes less typing (no need for print statements), and gives more immediate feedback (for example all the snippets demonstrating different ways of using traits can be tried one at a time).

      For execution in the interpreter, the WorldlyGreeter example needs to be rearranged, with the object definition coming before the class definition (which refers to it). (Am I alone in finding this example a bit contrived?)

      The only problem I had with following along in the interpreter was its lack of line-editing and history - but I just found another Scala tutorial here:

      http://blog.circleshare.com/index.php?/archives/41-Scala-Idioms,-Step-1,-Lists-and-Maps.html

      recommending the use of rlwrap to wrap the invocation of the interpreter, to provide these functions.

      http://freshmeat.net/projects/rlwrap/

      I haven't tried that yet - I'm just building it (via DarwinPorts), then I'll alias iscala to 'rlwrap scala', and then I should be happy.

      Thaks again for the article - I'm looking forward to the rest of the series.
    • jdnicolet
       
      Posts: 6 / Nickname: jdnicolet / Registered: October 27, 2003 7:58 PM
      Re: First Steps to Scala
      May 30, 2007 6:45 AM      
      Thank you for the great introduction.

      It looks like with traits, run-time substitution and functional programming, Scala has all that is needed to offer a STL-like library (STL for Standard Template Library in C++, one of the first attempt to deal with the functional paradigm, container and algorithms). Is there an underway attempt to build such a library ?
    • Eirik
       
      Posts: 1 / Nickname: eirikma / Registered: October 25, 2005 8:55 PM
      Re: First Steps to Scala
      June 19, 2007 11:49 PM      
      Great article. When do we get the guide for the next step?
    • Daniel
       
      Posts: 1 / Nickname: ddekany / Registered: June 21, 2007 9:54 AM
      Re: First Steps to Scala
      June 21, 2007 4:14 PM      
      "If an anonymous function consists of one method application that takes a single argument, you need not explicitly name and specify the argument. Thus, the following code also works:
      args.foreach(println)"


      Well, I know it's scandalous to ask but... is that because of that? Is that an anonymous function there at all, or rather I'm passing the println function itself? Because if I have a function with, for example, two arguments then I can also omit the parameters:

      def foo(f: (Int, Int) => Unit) {
      f(10, 20)
      }

      def bar(a: Int, b: Int) {
      println(a + " and " + b)
      }

      foo(bar) // <-- there!


      It seems to me pretty consistent with this, that also works:

      var f: (Int, Int) => Unit = bar
    • Daniel
       
      Posts: 11 / Nickname: djimenez / Registered: December 22, 2004 0:48 AM
      Re: First Steps to Scala
      May 14, 2007 6:37 AM      
      Great introductory article.

      A question about the map examples. What is it about method -> that is better than just defining the tuple? I mean, why is (1 -> "value") better than (1, "value")?
      • James
         
        Posts: 128 / Nickname: watson / Registered: September 7, 2005 3:37 AM
        Re: First Steps to Scala
        May 14, 2007 8:52 AM      
        > Great introductory article.
        >
        > A question about the map examples. What is it about method
        > -> that is better than just defining the
        > tuple? I mean, why is (1 -> "value") better
        > than (1, "value")?

        Good question. The only thing I can think of is that you could perhaps override the -> method, if that's allowed. Not sure that would be a good thing, though.
      • Andrew
         
        Posts: 1 / Nickname: andrewom / Registered: May 14, 2007 6:04 PM
        Re: First Steps to Scala
        May 14, 2007 11:19 PM      
        One advantage of the -> method is that brackets are not required (unlike the example in the article). This makes the syntax a lot more readable: e.g.

        val romanNumeral = Map(1 -> "I", 2 -> "II", 3 -> "III", 4 -> "IV", 5 -> "V")

        versus

        val romanNumeral = Map((1, "I"), (2, "II"), (3, "III"), (4, "IV"), (5, "V"))
        • Lex
           
          Posts: 3 / Nickname: lexspoon / Registered: October 9, 2006 11:13 PM
          Re: First Steps to Scala
          May 16, 2007 0:02 AM      
          Anyway, doesn't the -> version look nicer? Identifiers are not in short supply, so I don't see why there should be any effort to conserve them, unless....

          Ahh, maybe it appears to Artima readers to be a special case in the syntax. It is not. -> is just an operator, which in Scala can be used as a method name.
        • Bill
           
          Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
          Re: First Steps to Scala
          May 17, 2007 4:32 PM      
          > One advantage of the -> method is that brackets are not
          > required (unlike the example in the article). This makes
          > the syntax a lot more readable: e.g.
          >
          > val romanNumeral = Map(1 -> "I", 2 -> "II", 3 -> "III",
          > ", 4 -> "IV", 5 -> "V")
          >


          You're right, and I updated the article. I had originally had that form, but due to a misunderstanding with Martin added in the parens. Where the parens are needed is this form:


          import scala.collection.mutable.HashMap

          val romanNumeral = new HashMap[Int, String] + (1 -> "I") + (2 -> "II") + (3 -> "III") + (4 -> "IV") + (5 -> "V")
          • Mark
             
            Posts: 2 / Nickname: puzzler / Registered: June 9, 2006 11:07 AM
            Re: First Steps to Scala
            May 26, 2007 10:19 PM      
            After compiling WorldlyApp, if I type:
            scala WorldlyApp
            I get an error message that the file is not found.

            It only works if I type:
            scala -classpath . WorldlyApp

            How can I get scala to recognize the file without explicitly typing the classpath each time?

            I'm running on Windows XP Pro
        • Eric
           
          Posts: 1 / Nickname: ericjs / Registered: August 27, 2007 7:00 AM
          Re: First Steps to Scala
          August 27, 2007 0:08 PM      
          > One advantage of the -> method is that brackets are not
          > required (unlike the example in the article). This makes
          > the syntax a lot more readable: e.g.
          >
          > val romanNumeral = Map(1 -> "I", 2 -> "II", 3 -> "III",
          > ", 4 -> "IV", 5 -> "V")
          >

          > versus
          >
          > val romanNumeral = Map((1, "I"), (2, "II"), (3, "III"),
          > ), (4, "IV"), (5, "V"))
          >



          I have a hard time believing that most people will find the first construction more readable than the second. The parens provide a clear visual grouping of the pairs and the "->" makes for more clutter between the pairs where the lesser visual emphasis of the "," also helps make the grouping of pairs clearer.
          • Stanislas
             
            Posts: 2 / Nickname: graven / Registered: May 3, 2007 8:09 PM
            Re: First Steps to Scala
            September 7, 2007 1:36 AM      
            Well, lots of people find 2 + 3 * 4 + 5 * 6 + 7 clearer than 2 + (3 * 4) + (5 * 6) + 7. It's just a matter of habit, i think.
    • Jonathan
       
      Posts: 1 / Nickname: jdf / Registered: August 11, 2003 8:48 AM
      Re: First Steps to Scala
      December 16, 2007 8:50 AM      
      This article seems to require a few corrections to be up-to-date with the current release. In particular, Unit expressions (such as println), no longer result in a value being printed out by the interpreter:
      scala> println("Schmeggegge")
      Schmeggegge

      scala>

      I was especially stunned, and consider it kind of a bug, to see that vals can be reassigned:
      scala> val foo = "Hello, world!"
      foo: java.lang.String = Hello, world!

      scala> val foo = 12
      foo: Int = 12

      scala>
      • Morgan
         
        Posts: 37 / Nickname: miata71 / Registered: March 29, 2006 6:09 AM
        Re: First Steps to Scala
        December 30, 2007 8:47 AM      
        I am a long time C / Java programmer. Never used any functional languages, (well, I did use LISP very briefly many many years ago) most of this is new to me. Perhaps this ignorance shows in my (admittedly somewhat cynical) comments below.

        Overall, I love the fact that Scala runs in the JVM and I can import familiar Java classes. (And, I assume, 3rd party jars such as Apache) The parts work, I can use Eclipse, I'll almost certainly give Scala a try. But I have a lot of quibbles with the syntax. IMO, they got too creative / cutesie.

        You define an object as Singleton by calling it, DOH, object. Why not use the term "singleton"!

        If :: is pronounced "cons", why not type it as cons? Geez, its all of 2 extra characters. And it's clearer - I see "cons", I wikipedia LISP, and I get a lot of info on what it means, plus links to cdr, etc... And it's less likely to get confused with :::. A common programming bug in confusing = and ==, why design in :: and ::: which are visually even closer?

        treasureMap += 1 -> "Go to island.";

        for adding to a map is truly the most disgusting syntax ever. This is almost enough to make me writeoff the language. BTW, this syntax is longer than Java's

        treasureMap.put(1,"Go to island.");

        I'm extremely leery of syntactically important white space which seems common in Scala (if I'm understanding some of these alternative syntaxes right).

        "Sometimes the Scala compiler will require you to specify the result type of a method"

        I saw something like this in another article about variables. leave off declarations till it complains and you learn better. So you "save" typing and are ultra efficient by leaving off "int" or "void", but then you waste time when the compiler complains. Call me a sceptic.

        BTW, they should use void for void, not "unit". What the heck is unit?


        Finally, about all the functional parts. Will somebody please please post a useful example other than printing an array of strings? When the key benefit of FP that 1000s of posts of Artima are demanding be added to Java is the ability to go


        args.foreach((arg: String) => println(arg))


        instead of


        for (String arg : args)
        System.out.println(arg);


        I am, well, completely underwhelmed.
        • Ryan
           
          Posts: 2 / Nickname: ryani / Registered: January 3, 2008 10:05 AM
          Re: First Steps to Scala
          January 3, 2008 4:26 PM      
          > Finally, about all the functional parts. Will somebody
          > please please post a useful example other than printing an
          > array of strings?

          Here's a quick&dirty tool that I needed last year:
          - Read text from standard input until end of file, and output a histogram showing how often each line occurred in the file, in order from most common to least.

          Here's the first few lines of the output from my sample run:
          ("PIIIIIP",139627)
          ("CFPICFP",32482)
          ("PCCCCCP",28267)
          ("PFFFFFP",14319)
          ("PFFICCP",13534)
          ("CCICIIC",12192)

          Go ahead & write this in Java to start out.

          Here's my Haskell implementation:
          module Main where
          import qualified Data.Map as M
          import Data.List (foldl', sortBy)

          main = interact process

          process :: String -> String
          process = unlines . map show . organize . unpackHisto . buildHisto . lines

          buildHisto :: [String] -> M.Map String Int
          buildHisto = foldl' insertHisto M.empty

          insertHisto :: M.Map String Int -> String -> M.Map String Int
          insertHisto m s = M.insertWith (+) s 1 m

          unpackHisto = M.toList

          organize = sortBy s where s x y = compare (snd y) (snd x)

          A couple of comments about this:
          1) Sorry about the formatting; the forum seems to be eating the double-newlines in my code.

          2) I'm not golfing on this at all; this is the first code I wrote, it did what I wanted, and I was done with it.

          3) This is really just the tip of the iceberg; this is just a simple "pipeline" example. There's a lot more you can do; the functional style gives you the ability to factor out common functionality everywhere; if there's a certain type of for loop you write a lot, you can factor it out into a function.

          4) "interact" is just a regular function; in Scala it would have the type (String => String) => Unit. It takes a regular function that does string processing and applies it to stdin, writing the output to stdout. You could reasonably easily write "perlInteract" of the same type which read from files specified on the command line instead, with special treatment of "-" as stdin, but you wouldn't have to change the definition of "process" at all.
          • Morgan
             
            Posts: 37 / Nickname: miata71 / Registered: March 29, 2006 6:09 AM
            Re: First Steps to Scala
            January 3, 2008 9:42 PM      
            Here's a java version of line count. If I really wanted to I could save a few lines by converting the if else into a gross ? construct.


            public class Histo {

            static Comparator<Map.Entry<Comparable, Comparable>> VALUE_COMPARATOR = new Comparator<Map.Entry<Comparable, Comparable>>() {
            public int compare(Map.Entry<Comparable, Comparable> o1, Map.Entry<Comparable, Comparable> o2) {
            int result = o2.getValue().compareTo(o1.getValue());
            return (result != 0) ? result : o2.getKey().compareTo(o1.getKey());
            }
            };

            public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            HashMap<String, Integer> map = new HashMap();
            for (String s = br.readLine(); s != null; s=br.readLine()) {
            if (map.containsKey(s))
            map.put(s, new Integer(map.get(s) + 1));
            else
            map.put(s, 1);
            }

            ArrayList list = new ArrayList(map.entrySet());
            Collections.sort(list, VALUE_COMPARATOR);
            System.out.println(list.toString());
            }
            }
            • Ryan
               
              Posts: 2 / Nickname: ryani / Registered: January 3, 2008 10:05 AM
              Re: First Steps to Scala
              January 4, 2008 0:51 AM      
              Pretty good; my experience with Java has been that it's always really verbose, but this is reasonably short.

              My main comment revolves around this line:
              > Collections.sort(list, VALUE_COMPARATOR);

              VALUE_COMPARATOR is defined a long way away in the code, and it's 6 lines of code, the first of which is 125 characters long. Compare (pun not intended) to

              > sortBy (\o1 o2 -> compare (snd o1) (snd o2)) list
              or, in a "OO-functional hybrid" language, something like:
              > list.sortBy ((o1,o2) => o1.value.compareTo(o2.value))

              I think you'll agree that this is definitely more useful than "printing everything in a list" and demonstrates very well the power & succinctness of the style.

              An OO way to think about this is that closures/anonymous functions/whatever are just really lightweight classes with only one method (apply) and lots of nice syntax; you're just declaring a specialized class inline that automatically captures relevant local state into member variables.
              • Morgan
                 
                Posts: 37 / Nickname: miata71 / Registered: March 29, 2006 6:09 AM
                Re: First Steps to Scala
                January 5, 2008 2:20 PM      
                > Pretty good; my experience with Java has been that it's
                > always really verbose, but this is reasonably short.

                Thanks. Java is more verbose, but only partly due to Java. IMO much of it is due to poor coding at the tactical or strategic level.

                >
                > My main comment revolves around this line:
                > > Collections.sort(list, VALUE_COMPARATOR);
                >
                > VALUE_COMPARATOR is defined a long way away in the code,
                > and it's 6 lines of code, the first of which is 125
                > characters long.

                Agreed. Partly the Generics syntax.

                Java Comparators are certainly more verbose than in your example Haskell / Scala code. But one nice feature of them being more "real classes" is that one can chain them together, you can use a Factory pattern or similar to change things around (e.g., comparing European names vs. Chinese where the order switches) etc.

                The advantage of defining the VALUE_COMPARATOR several lines away in the code is that it is really a general purpose Comparator than much other code can now use or extend. Closures / anonymous classes are neither reusable nor extensible.

                I think the extra power is usually worth the extra work, but YMMV.
    • Chris
       
      Posts: 1 / Nickname: machershel / Registered: February 10, 2008 5:31 PM
      Re: First Steps to Scala
      February 10, 2008 11:52 PM      
      Here's my thought on the article:

      class HungryDeveloper extends Friendly {
      override def greet() = "Weow! I need more Scalazine"
      }

      Integrate this with Step 12 exercises and you'll know what I'm asking.... When do we get some more good stuff???! LOL

      Thanks for the article!

      Chris
    • Mark
       
      Posts: 1 / Nickname: messel / Registered: June 29, 2009 10:55 PM
      Re: First Steps to Scala
      June 30, 2009 3:58 AM      
      Thanks much for the introductory steps to scala. I prefer diving into a language after scanning some theory.

      Curious about a simple action thought, with scala/lift is there a simple way to retrieve an rss feed (one or two lines)?
    • Eric
       
      Posts: 1 / Nickname: ericbwilso / Registered: March 26, 2010 2:13 PM
      Re: First Steps to Scala
      March 26, 2010 7:48 PM      
      I like Scala. It is an attempt to be more productive in the tradition of Ruby and Rails.
      Some people think that Scala might allow difficult to read code on large projects with multiple people.
      For that reason I have been thinking about how to reduce such problems. Here are two ideas:

      1. Have a strict mode for the compiler which would force programmers into certain behaviors. ActionScript via FlexBuilder has a strict mode and I love it. With Scala an example of something to enforce in Strict mode would be a requirement that the programmer specify return types on methods/functions.

      2. Another suggestion is to have an optional explicit interface declaration for methods/functions. In Java we tag a class as implementing an interface with the implements keyword. I am suggesting having a similar implements keyword for methods. So a function that takes another function as an argument could specify an expected function interface instead of a function signature. The purpose would be to make it easier for a programmer looking at code (that he/she did not write on a very large project where the original author is gone) better be able to track which functions could be passed to a given function and which could not. This reduces the set of possible code paths to consider and thus increases understanding

      Thanks for considering this.
    • Venki
       
      Posts: 1 / Nickname: venkyvb / Registered: May 3, 2010 4:27 PM
      Re: First Steps to Scala
      May 6, 2010 3:54 PM      
      Great intro article that nicely steps through the various aspects of Scala !! Looking forward for more such articles.