The Wayback Machine - https://web.archive.org/web/20240918034102/https://www.geeksforgeeks.org/scala-sealed-trait/
Open In App

Scala | Sealed Trait

Last Updated : 19 Oct, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Sealed provides exhaustive checking for our application. Exhaustive checking allows to check that all members of a sealed trait must be declared in the same file as of the source file. That means that all the possible known members of a trait that must be included are known by the compiler in advance. So this gives us advantage to prevent mistakes in our code. 

Syntax : 

sealed trait X
class A extends X
class B extends X
class C extends X

Exhaustive checking is mostly used in type / pattern matching in scala. Let’s say we have a sealed trait X and classes that extends trait X. On matching sub-types of trait X we have to make sure that we inclusion of all known sub-types is a must. Below method would give us a warning. Though we would get the correct output, but this may could be lead to unexpected runtime crashes in our application. 

Warning: match may not be exhaustive
def obj(item: X) = item match {
   case A => //
   case B => //
}

Correct implementation would be like- 

def obj(item: X) = item match{
   case A => //
   case B => //
   case C => //
   or 
   case _ => //for covering all the remaining cases
}

Let us take a view on below program in file saves as language.scala:- 

Example : 

Scala




// Scala Program that illustrates sealed trait
// language.scala
sealed trait Geeks
{
    val article="not done"
}
 
// Class extends trait
class Scala extends Geeks
{
    override val article = "scala article"
}
 
// Class extends trait
class Java extends Geeks
{
    override val article = "java article"
}
 
// Class extends trait
class Csharp extends Geeks
{
    override val article = "csharp article"
}
 
// Creating object
object GFG
{
    // Main method
    def main(args: Array[String])
    {
        val s = new Scala
        val j = new Java
        val c = new Csharp
        println(checkArticle(s))
        println(checkArticle(j))
        println(checkArticle(c))
    }
     
    // Defined function
    def checkArticle(Article: Geeks): String = Article match
    {
        case s: Scala  => s.article
        case j: Java   => j.article
        case c: Csharp => c.article
        //exclusion of <strong>line 45</strong> would lead to warning
    }
}


Output : 

scala article
java article
csharp article
some important points
  • Sub-types of a trait are known in advance- Not including any of the sub-type of sealed class C in pattern match would give us warning. Such a warning tells you that there’s a risk your code might produce a Match Error exception because some possible patterns are not handled. The warning points to a potential source of run-time faults, so it is usually a welcome help in getting your program right. 
     
  • Sealed traits can only extend in the same source file as of sub-types- In above example, we have another class python in another scala file. Importing the trait geeks from language.scala we would get error message as below.
illegal inheritance from sealed trait bag
import geeks
class python extends geeks{
    val article="python article";
}
  • Sealed class is also mostly used in enums– Preventing illegal inheritance and using all the sub-type so to avoid exhaustive matching warnings. 
    Example :

Scala




// Scala Program that illustrates sealed trait
// By using Enumeration
sealed trait card extends Enumeration
 
// Class extends trait
case object CLUB extends card
 
// Class extends trait
case object HEART extends card
 
// Class extends trait
case object DIAMOND extends card
 
// Class extends trait
case object SPADE extends card
 
// Creating object
object obj1
{  
    // Main method
    def main(args: Array[String])
    {
        val card1 = HEART
        val card2 = CLUB
        val card3 = SPADE
        val card4 = DIAMOND
        println(checkcard(card1))
        println(checkcard(card2))
        println(checkcard(card3))
        println(checkcard(card4))
    }
     
    // Defined function
    def checkcard(x: card): String = x match
    {
         
        case HEART   =>"heart"
        case CLUB    =>"club"
        case SPADE   =>"spade"
        case DIAMOND =>"diamond"
    }
}


Output : 

heart
club
spade
diamond

 



Previous Article
Next Article

Similar Reads

Scala Trait Traversable | Set-1
Introduction: A root trait of the entire class of the Scala collections is Trait Traversable. It is available at the uppermost position of the collection hierarchy. It has uniquely one abstract operation, which is foreach. Here each of the operations are assured to be executed in a single-threaded approach. Syntax: def foreach[U](f: Elem =&gt; U) H
4 min read
Scala Trait Traversable | Set-2
prerequisite- Scala Trait Traversable | Set-1In the previous Set we have seen some of the operations performed by the Class Taversable. Now, in this Set we will perceive some more operations. These operations are as follows: Conversion operations: The Conversion operations are toList, toSeq, toArray, toStream, toSet, toMap, toIterable, and toIndexe
8 min read
Scala Trait Traversable | Set-3
Prerequisite : Scala Trait Traversable | Set-1 Scala Trait Traversable | Set-2 It is recommended to see (Set-1, Set-2) before this Set. The operations are as follows: Sub-Collection retrieval operations: The operations here are slice, drop, dropWhile, filter, filterNot, tail, take, takeWhile, and init. These operations are utilized to return some s
8 min read
Scala Trait Traversable | Set-4
Prerequisite :- Scala Trait Traversable | Set-1 Scala Trait Traversable | Set-2 Scala Trait Traversable | Set-3 It is recommended to view Set-1, Set2 and Set-3 before this one. The operations are as follows: Folds: The operations here are reduceRight, reduceLeft, /: or foldLeft, :\ or foldRight. This methods apply binary operation to the successive
6 min read
Scala | Trait App
App is a trait which is utilized to rapidly change objects into feasible programs, which is carried out by applying DelayedInit function and the objects inheriting the trait App uses this function to execute the entire body of the program as a section of an inherited main method. Note: trait App extends DelayedInit The Linear Super-types here are:
2 min read
Scala | Trait Mixins
We can extend several number of scala traits with a class or an abstract class that is known to be trait Mixins. It is worth knowing that only traits or blend of traits and class or blend of traits and abstract class can be extended by us. It is even compulsory here to maintain the sequence of trait Mixins or else the compiler will throw an error.
3 min read
Trait Linearization in Scala
Scala Linearization is a deterministic process which comes into play when an object of a class is created which is defined using inheritance of different traits and classes. linearization helps to resolve the diamond problem which occurs when a class or trait inherits a same property from 2 different concrete classes or traits. Syntax : trait C{} t
5 min read
Scala short &lt;(x: Short): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The &lt;(x: Short) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def &lt;(x: Short): Boolean Return Type: It returns true if this value is less than x, otherwise false. Example #1: // Scala p
1 min read
Scala short &lt;(x: Char): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The &lt;(x: Char) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def &lt;(x: Char): BooleanReturn Type: It returns true if this value is less than x, otherwise false. Example #1: C/C++ Code //
1 min read
Scala Extractors
In Scala Extractor is defined as an object which has a method named unapply as one of its part. This method extracts an object and returns back the attributes. This method is also used in Pattern matching and Partial functions. Extractors also explains apply method, which takes the arguments and constructs an object so, it's helpful in constructing
6 min read
Scala | Partially Applied functions
The Partially applied functions are the functions which are not applied on all the arguments defined by the stated function i.e, while invoking a function, we can supply some of the arguments and the left arguments are supplied when required. we call a function we can pass less arguments in it and when we pass less arguments it does not throw an ex
3 min read
Scala String indexOf(String str) method with example
The indexOf(String str) method is utilized to return the index of the sub-string which occurs first in the string stated. Method Definition: indexOf(String str) Return Type: It returns the index of the sub-string which is specified in the argument of the method. Example #1: // Scala program of int indexOf() // method // Creating object object GfG {
1 min read
Scala String contentEquals() method with example
The contentEquals() method is utilized to compare a string to the content of StringBuffer. Method Definition: Boolean contentEquals(StringBuffer sb) Return Type: It returns true if the content is equal to the stated string else it returns false. Example #1: // Scala program of contentEquals() // method // Creating object object GfG { // Main method
1 min read
Scala Keywords
Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Doing this will result in a compile-time error. Example: // Scala Program to illustrate the keywords // Here object, def, and var are valid ke
2 min read
Scala Int /(x: Int) method with example
The /(x: Int) method is utilized to return the quotient when the specified first int value is divided by the second int value. Method Definition: (First_Int_Value)./(Second_Int_Value) Return Type: It returns the quotient when the specified first int value is divided by the second int value. Example #1: // Scala program of Int /(x: Int) // method //
1 min read
Scala Int /(x: Short) method with example
The /(x: Short) method is utilized to return the quotient when the specified int value is divided by the short value. Method Definition: (Int_Value)./(Short_Value) Return Type: It returns the quotient when the specified int value is divided by the short value. Example #1: // Scala program of Int /(x: Short) // method // Creating object object GfG {
1 min read
Program to print Java Set of characters in Scala
A java Set of characters can be returned from a Scala program by writing a user defined method of Java in Scala. Here, we don't even need to import any Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples. Example:1# // Scala program to print Java Set // of characters in Scala // Creating object object
2 min read
How to Install Scala IDE For Eclipse?
In this tutorial, we'll look at how to set up the Eclipse IDE for Scala. This tutorial is for those who are new to Scala. Requirement for InstallationEclipse (Install link) if you don't know how to install Eclipse then refer to this article.JDK 11 (you may use JDK 6 onwards) Note: If you do not have JDK installed, you may get them from this link. I
2 min read
Scala Map size() method with example
The size() is utilized to find the number of key-value pairs in the stated map. Method Definition: def size: Int Return Type: It returns the number of elements in the map. Example #1: // Scala program of size() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -&gt; &quot;geeks
1 min read
Scala SortedMap addString() method with a start, a separator and an end with example
This method is same as addString() method but here a start, a separator and an end is also included. Method Definition: def addString(sb: mutable.StringBuilder, start: String, sep: String, end: String): mutable.StringBuilder Where, sep is the separator stated. Return Type: It returns the elements of the SortedMap in the String Builder and a start,
2 min read
Scala Iterator addString() method with example
The addString() method belongs to the concrete value members of the class AbstractIterator. It is defined in the class IterableOnceOps. It is utilized to append the elements of the Scala Iterator to a String Builder. Method Definition : def addString(b: StringBuilder): StringBuilder Return Type : It returns the String Builder to which the elements
1 min read
Scala String substring(int beginIndex, int endIndex) method with example
The substring(int beginIndex, int endIndex) method is utilized to find the sub-string from the stated String which starts and ends with the index specified. Method Definition: String substring(int beginIndex, int endIndex) Return Type: It returns string which is the part of the stated String. Note: It is same as sub-sequence method but the only dif
1 min read
Scala | Functions Call-by-Name
In Scala when arguments pass through call-by-value function it compute the passed-in expression's or arguments value once before calling the function . But a call-by-Name function in Scala calls the expression and recompute the passed-in expression's value every time it get accessed inside the function. Here example are shown with difference and sy
3 min read
Program to convert Java list to an iterator in Scala
A java list can be converted to an iterator in Scala by utilizing toIterator method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur. Now, lets see some examples and then discuss how it works in details. Example:1# C/C++ Code // Scala program to convert Java lis
3 min read
Scala Set &amp;() method with example
The &amp;() method is utilized to create a new set consisting of all elements that are present in both the given sets. Method Definition: Return Type: It returns a new set consisting of all elements that are present in both the given sets. Example #1: // Scala program of &amp;() // method // Creating object object GfG { // Main method def main(args
1 min read
Scala | Type Inference
Scala Type Inference makes it optional to specify the type of variable provided that type mismatch is handled. With type inference capabilities, we can spend less time having to write out things compiler already knows. The Scala compiler can often infer the type of an expression so we don’t have to declare it explicitly. Let us first have a look at
4 min read
Program to convert Java set of Shorts to an Indexed Sequence in Scala
A java set of Shorts can be converted to an Indexed Sequence in Scala by utilizing toIndexedSeq method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur. Now, lets see some examples and then discuss how it works in details. Example:1# // Scala program to convert
2 min read
Scala Int &lt;(x: Char) method with example
The &lt;(x: Char) method is utilized to return true if the specified int value is less than the char value, otherwise returns false. Here the char value is the ASCII value of the specified char. Method Definition: (Int_Value).&lt;(Char_Value)Return Type: It returns true if the specified int value is less than the char value, otherwise returns false
1 min read
Scala Int &lt;=(x: Double) method with example
The &lt;=(x: Double) method is utilized to return true if the specified int value is less than or equal to the double value, otherwise returns false. Method Definition: (Int_Value).&lt;=(Double_Value) Return Type: It returns true if the specified int value is less than or equal to the double value, otherwise returns false. Example #1: // Scala prog
1 min read
Scala Int &lt;=(x: Byte) method with example
The &lt;=(x: Byte) method is utilized to return true if the specified int value is less than or equal to the byte value, otherwise returns false. Method Definition: (Int_Value).&lt;=(Byte_Value) Return Type: It returns true if the specified int value is less than or equal to the byte value, otherwise returns false. Example #1: // Scala program of I
1 min read
Article Tags :