Open In App

Abstract types vs Generics in Scala

Last Updated : 27 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this discussion, we will explore abstract types and generics in Scala, highlighting their differences. Abstract types are types that include abstract members, while generics are types that can take other types as parameters. Let’s delve into the disparities between these two concepts.

Scala Abstract Types vs Generics

Abstract Type:

Abstract types are types that have undefined members, meaning their members lack a specific definition or value. Traits and abstract classes are common examples of abstract-type variables.

For example:

Consider a trait named Container, which has an abstract type Item and variable contents of type Item.

Scala Code

trait Container {

type Item

val contents: Item

}

In simpler terms, abstract types are placeholders for types that do not have a specific implementation yet. They allow us to define structures without committing to specific types until later.

Generics:

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

Scala Code:

class division[d]{

def division(u:z, v:z):z =>{

z=u/v;

}

}

// Here, division is a generic that accept type z values

Difference between Abstract types and Generics

Abstract types

Generics

Implemented or extended in Scala programs.

Takes a class type as a parameter.

Methods do not have definitions.

Uses definitions and other types.

Uses a ‘has-a’ relation.

Uses an ‘of’ relation.

Example: Baleno is a car.

Example: Array of Maps

Example:

“`scala

abstract class Animal {

type Food

val favoriteFood: Food

}

Example:

“`scala

class Container[T] {

def add(item: T): Unit

}

“`


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads