In Scala, forming a Generic Class is extremely analogous to the forming of generic classes in Java. The classes that takes a type just like a parameter are known to be Generic Classes in Scala. This classes takes a type like a parameter inside the square brackets i.e, [ ]. This classes are utilized explicitly for the progress of the collection classes in Scala. The sub-typing of generic types is invariant i.e, if we have two list types, A and B then List[A] is sub-type of List[B] if and only if type B is equivalent to type A.
Some points to remember:
- The symbol used for a type parameter of a simple type is A, like List[A].
- The symbols used for a type parameter of second, third, fourth, and so on, types in generic classes are respectively B, C, D, and so on.
- The symbol used for a key is A and for a value is B in Scala Map.
- The symbol used for a numeric value is N.
Note: Though this symbol conventions are provided, still any symbol can be used for the type parameters.
let’s discuss some examples below.
Here, the abstract class Divide has a type parameter z, and it is present in the square brackets so the class is generic type, this type parameter z can take up each and every data types. we have defined a method divide inside the Generic class which has two variables i.e, u and v and the data type of these variables is z. The class intDivide, as stated above take up integer types and the class doubleDivide, as stated above take up double types. Thus, the type parameter z was replaced by Int and Double data types. By this way sub-typing is possible in Generic classes.
The sum is : 100
Here, we saw generic type parameter for numeric values and so, we have used symbol N here though any symbol can be used as a type parameter for a generic types.
- Abstract Classes in Scala
- Difference Between Traits and Abstract Classes in Scala
- Private Classes in Ruby
- Understanding Classes and Objects in Java
- C# | Abstract Classes
- CSS | Pseudo-classes
- Abstract Classes in Python
- jQuery | Get and Set CSS Classes
- jQuery | multiple classes Selector
- Use of :even and :odd pseudo-classes with list items in CSS
- When to use static vs instantiated classes in PHP?
- Type Aliases vs Inline Classes
- Perl | Classes in OOP
- Kotlin Sealed Classes
- Kotlin Data Classes
- .pull-left and .pull-right classes in Bootstrap 4
- ES6 | Classes
- Kotlin Inline classes
- How to specify the order of classes in CSS ?
- How to apply two CSS classes to a single element ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.