Scala example “Hello World”

The scala programming language has become a popular replacement for Java.

Once you download scala, you can access it from the command line:

scala> Garys-MBP:search gary$ scala
Welcome to Scala version 2.11.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_25).
Type in expressions to have them evaluated.
Type :help for more information.

This is an excellent place to explore the language. For example, you can print to the screen:

scala> println("Hello World!")
Hello World!

To exit, press ctrl-C.

Now, let’s put some code in a file named hello.scala (you can also run this in the scala command line interpreter):

object HelloWorld { 
  def main(args: Array[String]) { 
    println("Hello, world!")
  } 
} 

On the command line, you can run this with the scala interpreter:

scala hello.scala 
Hello, world!

One of the benefits of using scala is the libraries that ship with the language.

For instance, let’s go back into the scala interpreter and make a list:

scala> val x = List(1, 2, 3)
x: List[Int] = List(1, 2, 3)

Now, type “x.” at the command line, and press tab twice: this will show you functions you can call on the list.

scala> x.
++             canEqual        drop        foreach           isDefinedAt          mapConserve    product             reverseMap      sorted         toIndexedSeq    unzip3         
++:            collect         dropRight   genericBuilder    isEmpty              max            productArity        reverse_:::     span           toIterable      updated        
+:             collectFirst    dropWhile   groupBy           isInstanceOf         maxBy          productElement      runWith         splitAt        toIterator      view           
/:             combinations    endsWith    grouped           isTraversableAgain   min            productIterator     sameElements    startsWith     toList          withFilter     
:+             companion       exists      hasDefiniteSize   iterator             minBy          productPrefix       scan            stringPrefix   toMap           zip            
::             compose         filter      head              last                 mkString       reduce              scanLeft        sum            toSeq           zipAll         
:::            contains        filterNot   headOption        lastIndexOf          nonEmpty       reduceLeft          scanRight       tail           toSet           zipWithIndex   
:\             containsSlice   find        indexOf           lastIndexOfSlice     orElse         reduceLeftOption    segmentLength   tails          toStream                       
addString      copyToArray     flatMap     indexOfSlice      lastIndexWhere       padTo          reduceOption        seq             take           toString                       
aggregate      copyToBuffer    flatten     indexWhere        lastOption           par            reduceRight         size            takeRight      toTraversable                  
andThen        corresponds     fold        indices           length               partition      reduceRightOption   slice           takeWhile      toVector                       
apply          count           foldLeft    init              lengthCompare        patch          repr                sliding         to             transpose                      
applyOrElse    diff            foldRight   inits             lift                 permutations   reverse             sortBy          toArray        union                          
asInstanceOf   distinct        forall      intersect         map                  prefixLength   reverseIterator     sortWith        toBuffer       unzip                          

Using these techniques you can start exploring the available APIs.

Leave a Reply

Your email address will not be published. Required fields are marked *