Scala Sequence Comprehensions, Generic Classes and Inner Class Example

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;

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-450x215

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

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-450x375

Consider an example of a comprehension which returns Unit.

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 Generic Classes

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

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;

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-268x450

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

By admin

Leave a Reply