Monday, September 12, 2016

Array Example : Value & Type Paramaterization

scala> // Parameterize Class instance with Value & Type

scala>

scala> /*******************************************
     |    Creating & Initializing an Array #77
     | *******************************************/
     | //Option 1
     | // Here 'String'  is Parameterized Type
     | //      '2'       is a Parameterized Value
     | // Square Bracket ([]) is used to Parameterize a Type
     | val subject:Array[String] = new Array[String](2)
subject: Array[String] = Array(null, null)

scala> subject.update(0, "english")

scala> subject.update(1, "math")

scala>

scala> //Option 2

scala> val subject = new Array[String](3)
subject: Array[String] = Array(null, null, null)

scala> // During assignment Parenthesis calls the 'update()' method

scala> // passing both the Array index & value assigned

scala> subject(0) = "english"

scala> subject(1) = "math"

scala>

scala> // Option 3

scala> // Here Parenthesis in 'Array' calls the apply() factory

scala> // method of the Companion Object (Here Array is a

scala> // Companion Object rather than the Class)

scala> val subject = Array("english", "math")
subject: Array[String] = Array(english, math)


scala> /*******************************************
     |    Accessing an Array #77
     | *******************************************/
     |
     | //Option 1
     | for(i <- (0).to(1)) {
     |    // Note : Parenthesis is used to access an Array element
     |    //        unlike Square brackets that is used in Java
     |    //        #79
     |    print(subject.apply(i))
     | }
englishmath
scala>

scala> //Option 2

scala> // If a method ('to' in our case) takes only 1 parameter

scala> // '.' and Parenthesis cna be omitted (We should also have a

scala> // receiver for the method call...in our case 'i')

scala> for(i <- 0 to 1) {
     |    //Note here..the apply() method is called implicitly
     |    print(subject(i))
     | }
englishmath