Scala Hello World

Posted on Monday, March 4, 2013



This is just a real quick Scala HelloWorld program.  I am going to install Scala on my Windows 7 box and on an ubuntu server I have handy.


Install Scala on Win 7


In this section I will go over installing Scala in a Windows 7 environment.

First we need to download  Scala for windows

Go to http://www.scala-lang.org/downloads and download scala.




Download the .zip archive.  I tried the MSI file but it placed files in different directories that what I wanted.   At any rate, download the zip file



I created a Scala folder at C:\Scala\scala-2.10.0 and unzipped the scala-2.10.0 version into it.


Now the bin scala bin directory at C:\Scala\scala-2.10.0\bin (in my case) needs to be added to your computers path variable.




Click on Start,  right click on Computers and click on Properties




Click on Advanced System Settings




Click On Environment Variables




Select Path and click Edit





Enter the  ;C:\Scala\scala-2.10.0\bin  at the end of the variable value and click OK (do not forget the  ;  before the path)




Testing win7


Now open a command prompt and run this command


> scala




And the scala prompt comes up and the scala interpreter opens.



Cygwin


When I tried to do the same thing from Cygwin I got this error

Registry key 'Software\JavaSoft\Java Runtime Environment\CurrentVersion'
has value '1.7', but '1.6' is required.



I have Java 1.7 and 1.6 on my machine,  1.7 is the default.  

Rather than fiddle with this it looks like the scala download page's unix download supports Cygwin





From Cygwin run the following command to download the .tgz file from scala and untar it



> wget http://www.scala-lang.org/downloads/distrib/files/scala-2.10.0.tgz
>  tar xf scala-2.10.0.tgz



Then edit .bash_profile


> vi .bash_profile





Add the following lines to the bottom of the file


export SCALA_HOME=~/scala-2.10.0
export PATH=$SCALA_HOME/bin:$PATH




I am still getting the error…



Doing a quick look around the internet I found this forum talking about this issue  http://www.coderanch.com/t/549037/java/java/basic-HelloWorld-app-wrong-version [1]

From this site I realized that I had my JAVA_HOME set to C:\Windows\System32\java\bin where I placed an older version of jave.ex and javac.exe about a year ago for some reason I set this up like this (I forget why)

But this was the problem  I need to update the JAVA_HOME setting on the Windows machine 




Click on Start,  right click on Computers and click on Properties





Click on Advanced System Settings




Click On Environment Variables




In my case I had not set JAVA_HOME here so I clicked new




Enter JAVA_HOME and the location of your jdk folder in my case it is C:\Program Files\Java\jdk1.7.0.

Then click OK


I also had to remove a JAVA_HOME definition in my .bashrc file I had set prior. 
Open a new Cygwin window for the new JAVA_HOME to take effect.





Retrying running scala again in Cygwin works!




Install Scala on Ubuntu



From the command line you could run the following


> sudo apt-get install scala


If you do this on Ubuntu 12.10 you get Scala 2.9.2 using OpenJDK




That is all well and good but I would rather use Java 1.7 from Sun and the latest scala build 2.10.0 so to do that install you need to first install java 1.7 to do that run the following commands


>  sudo apt-get purge openjdk*
>  sudo apt-get install python-software-properties
>  sudo add-apt-repository ppa:webupd8team/java
>  sudo apt-get update
>  sudo apt-get install oracle-java7-installer
>  java -version





Run the following command to download the .tgz file from scala and untar it


  > wget http://www.scala-lang.org/downloads/distrib/files/scala-2.10.0.tgz
  >  tar xf scala-2.10.0.tgz


Now place the scala program in /usr/bin/scala
And make a ln to it



    > sudo mkdir /usr/lib/scala
    > sudo mv scala-2.10.0 /usr/lib/scala/
    > sudo touch /usr/bin/scala
    > sudo ln -fs /usr/lib/scala/scala-2.10.0/bin/scala /usr/bin/scala
    >  sudo chmod a+x /usr/bin/scala




Then edit my .bashrc file  (I had set JAVA_HOME here before)


  > cd
  > vi .bashrc


Updated JAVA_HOME to



 export JAVA_HOME=/usr/lib/jvm/java-7-oracle




Open a new terminal and run scala


  > scala




Here you can see scala is using Java 1.7_0_15 from the JAVA_HOME variable.



Hello World


Scala Interperter


The simplist "Hello World" is made by using the scala interperter.

Simply start the scala interpreter by running this command



  > scala



Then from within the scala interpreter write this line of code and press enter to run it.



 scala> println("Hello World")




To quit the scala interpreter press ctrl-d
Scala Program

Using the scala interpreter is a little foreign to me as a Java programmer,  I want to make the hello world Scala Program.
And run it using some main function


First write the program


  > vi HelloWorld.scala


Here is the code


object HelloWorld {

    def main(args: Array[String]) {

          println("Hello World!")
    }
}





Now compile it


  > scalac HelloWorld.scala


This will create a HelloWorld$.class and HelloWorld.class





To run the command enter the following


  > scala HelloWorld





A more scala way to write the code would be the following


object HelloWorld extends App{
    println("Hello World!")
}




Scala Code


I am still new to scala so I may be saying this incorrectly…

A class with constructor in java could look like this.


public class myClass{
    //Read only variables
    private int x;
    private int y;

    public myClass(int x, int y){
        this.x = x;
        this.y = y;
    }

    public int getX() {
       return this.x;
    }

     public int getY() {
         return this.y;
     }
}


The long way to write this in scala would be


class myClass {
    private var x = 0
    private var y = 0

    def this(x: Int, y: Int) {
        this() //Calls primary constructor
        this.x = x
        this.y = y
    }

    def getX = x
    def getY = y
}


This works but uses an auxiliary constructor
   def this(x: Int, y: Int)

All auxiliary constructors must start with a call to a previous auxiliary constructor or the primary constructor. (in this case it calls to primary using this()

It has two private class members that are Int objects.   It also defines a way to read those variable using def getX = x and def getY = y

There is a far better way to do this in Scala using the primary constructor you can make this much cleaner and shorter.


Here is the code using the primary constructor



class myClass (val x: Int, val y: Int) {
}


The class definition combines a constructor to create the primary constructor.  x and y become class members.   Any class member, if not private automatically is provided getters and setters  (if its only a val it only has getters)



Looking back at the hello world scala program


object HelloWorld extends App{
    println("Hello World!")
}



You can see its an object and not a class?  What does this mean?  A Scala classes have no static members, instead Scala provides a way to create singleton objects.   Using object where class should be just says this will be a singleton (a single object)


extends App means this class inherits from the trait APP which defines the main method (an here I am not sure exactly what it does, but the

basic result is it calls the primary constructor of the HelloWorld object)


It also gives you the args from the command line.  If you update your scala program to the following and recompiling it.


object HelloWorld extends App {
      println("Hello World!")
      if(args.length > 0) {
           println(args(0))
      }
}


Then running this command



   >  scala HelloWorld Test



I get the following output





Script


You can run scala from a script if need be.

Here is an example

First open it and edit it



  > vi myscript.sh




#!/bin/bash

exec scala "$0" "$@"
!#
object HelloWorld {
  def main(args: Array[String]) {
    println("Hello World! " + args.toList)
  }
}
HelloWorld.main(args)


Then run this command



  > bash myscript.sh test this out



I am not sure if I would use this scripting feature, but it is interesting.






References
[1]        Problem with basic HelloWorld app - wrong version? http://www.coderanch.com/t/549037/java/java/basic-HelloWorld-app-wrong-version
                Accessed 03/2013

No comments:

Post a Comment