5

Do you know about Union Types in Scala 3.0?

 3 years ago
source link: https://blog.knoldus.com/union-types-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 Union Types in Scala 3.0?

Reading Time: 2 minutes

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

What is Union?

Union of two things under consideration, is the collection of elements which can belong to either of them or both of 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, union of s1 and s2 will be:
Set s = {2, 3, 5, 4, 6}
What we can infer from it is:
s(union of s1 and s2) is a set which belongs to s1(2, 3, 5) or s2(2, 4, 6) or both s1 and s2(2), i.e ‘s’ is a collection of prime numbers, even numbers and even prime number.

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 get to know about s(union of type s1 and type s2):
s is a type which is s1 or s2 or s1 and s2 both at any given point in time.
Complete example would look something like given below:

trait LivingThing
  
trait NonMotile

Now, if we have a method isPlant() which takes in an object which can be LivingThing or NonMotile or both LivingThing and NonMotile, then it would be like:

def isPlant(obj : LivingThing | NonMotile) : Boolean =
{
  if (obj.isInstanceOf[LivingThing & NonMotile]) true
  else false
}

Here, in the method signature we have specified that this method takes a parameter which is LivingThing or NonMotile or it can be both. 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 isPlant() for successful execution is :

class Tree extends LivingThing with NonMotile // isPlant(new Tree) returns true

class Human extends LivingThing // isPlant(new Human) returns false

class Furniture extends NonMotile
 // isPlant(new Furniture) returns false

So, in isPlant() method, “obj” should be a sub-type of LivingThing or NonMotile or both LivingThing and NonMotile, for it to execute successfully.

I hope you understand what Union 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