Monday, June 1, 2015

Hello World with some extra features in Scala

The ubiquitous "Hello World" program has been written in Scala to highlight some of the features of the language. A compiled scala programs runs on jvm. It can also import all the java classes as the example below shows.


//  _ the underscore is like wildcard to import all the classes of math package
import scala.math._
/**
 * @author Rajeev
 *
 */
// object keyword automatically created a singleton object for the class HelloWorld
object HelloWorld {

/*
just like java main is the starting point
we say 'obj : type' in scala rather than 'type obj' in java as type can be automatically inferred in many cases
def indicates it is a function
Unit indicates it is returning void
Array[String] means array of type string
without = sign in the definition it will become a procedure which returns nothing rather than a function
*/

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

// greet invoked like any method in java but it is passing a function, myFunc, in the arguments too
    println(HelloWorld.greet("Rajeev",myFunc))
     }
/* note that the parameter type => indicates it a by name function and wherever its name occurs in the current function it will be executed.
We don't neeed {} for single line function definitions
*/
  def greet (raj :String, afunc : => String) : String = "Hello World " + raj + " " + afunc + " " + math.Pi
  def myFunc =  "myfunc"
}