Working with types in Scala can be challenging in many ways. The deeper you dig into the complexity of this subject, the more difficult is to find the right path. In this short post, I will be explaining some of the most fundamental of Scala type system — the type bounds. Enjoy!

What is type bound?

A type bound is nothing more than a mechanism to add restrictions to the type parameters. When passing a type to let’s say a class, we can limit to what types we want to allow. This mechanism allows for greater control over our code and hopefully making it more robust.

There are 3 distinct type bounds available in Scala — upper bound, lower bound and upper and lower combined. The chapters below explain how to use each of them.

Upper type bound

An upper type bound constraints a type A to be a subtype of B. The Scala notation looks like this:

class SomeClass[A <: B]

The example above defines the type of A as a subtype of B. To understand it better, let’s use some better example:

trait Eatable

class Vegetable extends Eatable
class Meat extends Eatable
class Potato extends Vegetable
class Beef extends Meat
class Orange extends Eatable
class Vegan[A <: Vegetable]
class Carnivore[A <: Meat]
class Food[A <: Eatable]
val vegan = new Vegan[Potato] // works fine
val mixed = new Carnivore[Potato] // error - type argument doesn't conform to type parameter bound
val all = new Food[Beef] // all good

As seen on a few examples above, the mechanism is pretty easy to use. The class Vegan, requires its type parameter to a subtype of Vegetable, which is exactly what Potato is. On the other hand, class Carnivore requires its parameter type to be a subtype of Meat, which Potato isn’t hence the error. The Food class accepts any class that extends Eatable trait - a Beef is one of them.

#scala #functional-programming #coding #programming #tutorial #function

Scala Type Bounds: What is type bound?
1.55 GEEK