GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Showing posts with label Scala. Show all posts
Showing posts with label Scala. Show all posts

Tuesday, December 21, 2010

List Data Structure In Scala

To create list in scala, use:
scala> val data = List("lady gaga","barack obama","larry page")

To access an element of list, use its index:
scala> println(data(2))
larry page

To iterate the whole elements, use:
scala> for( d <- data){
     | println(d)
     | }
or
scala> data.foreach(println);
lady gaga
barack obama
larry page


To know what the size, use:
scala> data.length

To get the first element, use:
scala> data.head

To get the last element, use:
scala> data.last

To reverse the elements order, use:
scala> data.reverse
         
    
Share/Bookmark

Array In Scala

To create an array in scala, type:
scala> val data = new Array[String](3);
scala> data(0) = "lady gaga"
scala> data(1) = "luna maya"
scala> data(2) = "aura kasih"

To access an element, use ( ) operator, not [ ], with the index:
scala> println(data(0));

To iterate to the whole elements, use:
scala> for ( d <- data){
     | println(d);
     | }
or
scala> data.foreach(println);
lady gaga
luna maya
aura kasih 
       
Share/Bookmark

While Loop In Scala

To make a while loop, use:

scala> var i = 0;
scala> while(i<5){
     | println(i+". Hello");
     | i += 1;   // doesn't work with i++
     | }  
0. Hello
1. Hello
2. Hello
3. Hello
4. Hello
               
Share/Bookmark

Method In Scala

This is the simplest method example:

scala> def hello() = println("Hello World");
or
scala> def hello() = { println("Holla World"); }

To call it, just type:
scala> hello();

Below is a sample for method with parameters:
scala> def data(name: String, age: Int) = { println("Name: 
     | "+name); println("Age: "+age); }

To call it, type:
scala> data("Lady Gaga",24)
Name: Lady Gaga
Age: 24

Method with return:
scala> def addTwo(x: Int): Int = { return x+2; }
or
scala> def addTwo(x: Int): Int = { x+2; }
Share/Bookmark

If Else In Scala

Just type this so simple code:

scala> var x = 4
scala> if (x>5) {
     | println("The First Block");
     | }else{
     | println("The Second Block");
     | }    
Share/Bookmark

Basic Scala

In Interactive mode, type:

scala> println("Holla World")
Holla World

scala> 2+3
res1: Int = 5

To use a variable, you need to use var keyword:
scala> var x = 45
a: Int = 45
scala> println(x)
45
scala> var msg = "Holla World From Scala"
scala> println(msg)
Share/Bookmark

The First Program In Scala

Type this one in scala environment interactively:

scala> object HelloWorld{
     | def main(args: Array[String]){
     | println("Hello World From Scala")
     | }
     | }

To execute above code, type:
scala> HelloWorld.main(null)

Or you can use:
scala> object Hello extends Application{
     | println("Hello World From Scala")
     | }


To run it, just type:
scala> Hello
 
Share/Bookmark