Home » Scala language

Scala Sealed Trait

Sealed trait in Scala is used to check for exhaustive checking. In this tutorial on the sealed trait, we will learn about sealed traits in Scala along with sample codes.
Submitted by Shivang Yadav, on December 25, 2019

Sealed Trait

Sealed Traits in Scala are used to allow exhaustive checking in the Scala application. Due to this exhaustive checking, the program allows the members of the sealed trait to be declared in a single file.

This helps the compiler by providing a list of all possible members of the trait beforehand. Which reduces the chances of errors in our code.

Let's see the block of code, here we have a trait whose all members are declared with it.

sealed trait trait1{}
class class1 extends trait1
class class2 extends trait1
class class3 extends trait1

Now since we have a sealed trait, exhaustive checking will we used which will require all the sub-types of the trait to be included otherwise it will throw a warning.


sealed trait royalEnfield
	val speed= 110; 
class bullet extends royalEnfield 
	override val speed = 125; 
class thunderbird extends  royalEnfield
	override val speed = 137; 
class continental extends royalEnfield 
	override val speed = 152; 
object myObject 
	def main(args: Array[String]) 
	    val bullet350 = new bullet;
	    val thbd350 = new thunderbird;
	    val gt = new continental;
	def topSpeed(Article: royalEnfield): Int = Article match
		case bullet350: bullet =>bullet350.speed; 
		case thbd350: thunderbird =>thbd350.speed; 
		case gt: continental =>gt.speed; 



Some features of Sealed Trait

  • The compiler knows all the sub-types of the trait in advance which help it avoiding errors by throwing warnings.
  • The inheritance of a sealed trait is allowed only by classes inside the file that declares the trait. In an external file, if a class tries to extend the trait error will be thrown by the compiler.
  • To prevent the above type of inheritance, sealed traits are generally used with enums.

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.