Home » Scala language

Abstract types vs Generics in Scala

Scala Abstract types vs Generic: Here, we are going to learn about the abstract types and generics, differences between the abstract types and generics in Scala. An abstract type is a type that contains abstract members and a generic type takes a type as a parameter. In this article, we will learn the difference between these types.
Submitted by Shivang Yadav, on August 11, 2019

Scala Abstract types vs Generics

Abstract type

Abstract types have abstract members i.e. their members do not have the definition or the values. Traits and abstract classes are abstract type variables.

For example,

    trait  trai { 
        type T
        val variable : T


Generic classes are those classes that have classes or other types as parameters.

    class division[d]{
	    def division(u:z, v:z):z =>{
    // Here, division is a generic that accept type z values

difference between Abstract types and Generics

Some points of the difference between Abstract types and Generics in Scala...

  • Abstract type in implement or extended in a Scala Program whereas Generics take a class type as the parameter.
  • In Abstract type methods do not have definitions whereas the generics use definition and use other types.
  • Abstract type uses a 'has-a' relation and generics use an 'of' relation.
  • Example of an abstract type, Baleno is a car.
    Example of a generic type, array of maps.

In Scala, an abstract class or a trait can be abstract type whereas a class that is abstract or simple can be generic if it accepts any type.

A class can be abstract as well as generic also, as both concepts can work together as well as individually. You can create a Scala class that generic and abstract as:

    abstract class product[x] {
	    def product(a:x , b:x ): x 

The method to this class has no definition which means it is abstract and the class uses data of type x which means it is a generic one.

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.