7

Do you know about Intersection Types in Scala 3.0, Dotty?

 3 years ago
source link: https://blog.knoldus.com/intersection-types-in-scala-3-0/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Do you know about Intersection Types in Scala 3.0, Dotty?

Reading Time: 2 minutes

You might have learnt intersection of subsets in mathematics, similarly, we have intersection types in Scala 3.0 as well. Let’s see, how can we use intersection types while programming in scala:

What is Intersection or Conjunction?

Intersection of two or more things under consideration, is the collection of common things among them. Let’s understand with respect to set theory:
Set s1 = {2, 3, 5}, set of first three primes
Set s2 = {2, 4, 6}, set of first three evens
Now, intersection of s1 and s2 will be:
Set s = {2}
What we can infer from it is:
s(intersection of s1 and s2) is a set which belongs to s1 as well as s2, i.e ‘s’ is a set of prime numbers which are also prime.

Venn's Diagram for Primes and Evens.

Now, we can see what it means in terms of scala 3.0:
Consider above mentioned sets as types and their elements as their members. So, here’s what we can infer about s(intersection of type s1 and type s2):
s is a type which is s1 and also s2 at any given point in time.
Complete example would look something like given below:

trait Respiration {
  def breathe() : Unit
}
  
trait Lungs extends Respiration
  
trait Gills extends Respiration
  
trait Move {
  def move(x : Int, y: Int) : Unit
}

Now, if we have a method run() which takes in an object which can move and respire would be:

def run(obj : Move & Respiration): Unit = {
  println("I ran 100 miles")
}

Here, in the method signature we have specified that this method takes a parameter which can move and respire. Operator & is available in scala 3.0 and which can only be compiled by dotc compiler. So, a sample class whose object can be passed to run() for successful execution is :

class Human extends Move with Lungs {
  override def move(x: Int, y: Int): Unit = {}

  override def breathe(): Unit = {
  }
}

So, in run() method, “obj” should be a sub-type of both Move and Respiration traits, for it to execute successfully.

I hope you understand what Intersection types in Scala 3.0, Dotty are all about. For more details visit official documentation
Thank you.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK