Home »
Scala
Scala Sealed Trait
By IncludeHelp Last updated : October 26, 2024
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.
Syntax
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.
Example of Sealed Trait
sealed trait RoyalEnfield {
val speed: Int
}
class Bullet extends RoyalEnfield {
override val speed: Int = 125
}
class Thunderbird extends RoyalEnfield {
override val speed: Int = 137
}
class Continental extends RoyalEnfield {
override val speed: Int = 152
}
object MyObject {
def main(args: Array[String]): Unit = {
val bullet350 = new Bullet
val thunderbird350 = new Thunderbird
val continentalGT = new Continental
println(topSpeed(bullet350))
println(topSpeed(thunderbird350))
println(topSpeed(continentalGT))
}
def topSpeed(article: RoyalEnfield): Int = article match {
case bullet: Bullet => bullet.speed
case thunderbird: Thunderbird => thunderbird.speed
case continental: Continental => continental.speed
}
}
Output
125
137
152
Features of Sealed Trait
Key features of sealed traits in Scala include the following:
- 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.