Scala Sequence Comprehensions, Generic Classes and Inner Class Example

Filed Under: Scala

A sequence comprehension statement consists of a generator part which generates a list of values from the specified range of inputs and a statement which operates on these generated elements which is then stored in the output list to be returned at the end of computation. For example;


object Sequence {
 def main(args:Array[String]) {
 def increment(from: Int, to:Int):List[Int] =
    
 for(i <- List.range(from,to) if  i % 5 == 0) yield i    
println(increment(1,30))
}
}

In this example we are creating a method that accepts two Integer parameters from and to that takes the range of the numbers. For every number starting from 1 we are checking whether the number is divisible by 5 as i%5 == 0 which prints only the numbers divisible by 5 in the range 1-30.

Below image shows the output produced and you can see that they all are divisible by 5.

scala-sequence-comprehension-example

Consider an example which returns a pair of numbers when multiplied is equal to specified value y.


object Seq {
   def main(args:Array[String]){
     def multiples(x:Int, y:Int) =
       for(a <- 0 until x;
       b <- a until x if a * b == y) yield
       Tuple2(a,b);
       multiples(42,40) foreach {
         case(a,b) =>
           println("(" + a + " ," + b + ")")
       }
   }
}

In this example we are defining a method “multiples” that accepts two integer argument x and y . We are checking for the condition that variables a and b when multiplied gives the value equal to the value of y specified by the user. The result is a pair of numbers as shown in the below image.

scala-comprehensions-example

Consider an example of a comprehension which returns Unit.


object Comprehension {
   def main(args:Array[String]){
 for (i <- Iterator.range(0, 15);
 j <- Iterator.range(i, 15) if i*j == 12)
 println("(" + i + ", " + j + ")")
 }
}

The yield keyword should not be used for such comprehensions. The range of numbers is specified using the Iterator.range. Above code produces following output.

scala-iterator-range-example

Scala Generic Classes

Scala supports generic classes which are useful for the development of collection classes. For example;


object GenericClass {
 
  def main(args:Array[String]) {
  abstract class Multiply[x] {
 def multiply(a: x, b: x): x;
  }

  class intMultiply extends Multiply[Int] {
 def multiply(a: Int, b: Int): Int = a * b;
  }

  class DoubleMultiply extends Multiply[Double] {
 def multiply(a : Double, b : Double) : Double = a * b;
  }
 
   val m1 = new intMultiply().multiply(20,15);
   val m2 = new DoubleMultiply().multiply(20.34, 6.56);
   println(m1);
   println(m2);
}
}

In this example we declare an abstract class Multiply with x that can accept any data type and define multiply method with a and b variables of x data type. Now we define two classes intMultiply, DoubleMultiply that accepts Integer and Double types respectively. We create m1 and m2 and call the methods multiply by passing the arguments.

Scala Inner Classes

A class can be defined inside another class in Scala which is termed as an inner class. The inner class is bound to the outer object. For example;


class Add {
  class Addtwonumbers {
 var a = 12;
 var b = 31;
 var c = a + b;
    
  }
}

object Innerclass {

def main(args:Array[String]) {

val a1 = new Add
val a2 = new Add
val b1 = new a1.Addtwonumbers
val b2 = new a2.Addtwonumbers

b1.a = 30;
b1.b = 45;
b2.a = 55;
b2.b = 24;
println(s"b1.a = ${b1.a}")
println(s"b1.b = ${b1.b}")
println(s"b2.a = ${b2.a}")
println(s"b2.b = ${b2.b}")
println(s"Result = ${b2.c}")

}
}

In this example we define an Outer class Add and inside this class we define one more class Addtwonumbers which is the inner class. In the inner class Addtwonumbers, we are defining variables a, b, c and storing result of a+b in c.

We are assigning values for variables a and b and accessing it by creating instances of the outer class and then instance of inner class through this outer class instance. Below image shows the output produced when main method of Innerclass is invoked.

Scala-inner-class-example

That’s all for a brief introduction to sequence comprehensions, generics and inner classes in Scala programming language.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages