Scala Abstract Types With Examples

The type whose identity is not known precisely can be termed as abstract type.

Scala Abstract Members

A member is said to be abstract if the member does not have a complete definition in the class. These are implemented in the subclasses. For example;

Student trait declares a type X where the type of X is unknown. A method total marks returns type X and members marks1, marks2 are of type X. Here X is called as abstract type.

Now lets us implement the type X in a subclass.

We are creating class Adam that extends the student class and defines type X as Integer. The total marks method add the marks m1 and m2. The age variable is initialized to 7.

Abstract vals

The abstract val takes the form as;

The variable name and type is specified here but not the value of the variable name.

For example;

The val declaration can be used in a class when you don’t know the correct value but we know that the value remains unchanged in each instance of the class.

An abstract val declaration constrains its legal implementation – def or val.

For example;

An abstract class Student id created with value variable and method with the keyword def.

A class Rob is created extending Student and the method is defined with the keyword val which is allowed. The code will compile successfully.

A class Micheal is created extending the student class and the value and method is defined using the keyword def. This will throw an error as overriding is not allowed. Below image shows the above code execution in scala shell.


Abstract vars

Abstract var defines a name and type but not value. Consider an example which defines two abstract variables – name and age as below.

The vars declared are equipped with getter and setter methods.

Initializing abstract vals

Abstract vals allows us to provide the details in subclass when missed in superclass. For example;

Here the variables obtained and total are abstract vals and the values are not defined.

Here we declare variable scale and use them in the trait as below.

The exception in this example was thrown because total still had its default value of 0 when trait student_percent was initialized, which caused the require invocation to fail.


Pre-initialized fields

Pre-initialized fields allows to initialize the fields of a subclass before the superclass is called. The field definition is placed in the braces before the superclass constructor call. For example create trait student_percent as;

Now call the trait student_percent by initializing values for “obtained” and “total” as

Output:res22: student_percent = Percentage secured is80.0

The fields can be initialized in object definition as;

Below image shows the above code execution in scala shell.


That’s all for abstract types in Scala programming, we will look into annotations in coming posts.

By admin

Leave a Reply

%d bloggers like this: