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.
Note:
- The Mixins traits are utilized in composing a class.
- A Class can hardly have a single super-class, but it can have numerous trait Mixins. The super-class and the trait Mixins might have identical super-types.
Now, lets see some examples.
- Extending abstract class with trait
Example :
trait Display
{
def Display()
}
abstract class Show
{
def Show()
}
class CS extends Show with Display
{
def Display()
{
println( "GeeksforGeeks" )
}
def Show()
{
println( "CS_portal" )
}
}
object GfG
{
def main(args : Array[String])
{
val x = new CS()
x.Display()
x.Show()
}
}
|
Output:
GeeksforGeeks
CS_portal
Here, the correct order of Mixins is that, we need to extend any class or abstract class first and then extend any trait by using a keyword with.
- Extending abstract class without trait
Example :
trait Text
{
def txt()
}
abstract class LowerCase
{
def lowerCase()
}
class Myclass extends LowerCase
{
def lowerCase()
{
val y = "GEEKSFORGEEKS"
println(y.toLowerCase())
}
def txt()
{
println( "I like GeeksforGeeks" )
}
}
object GfG
{
def main(args : Array[String])
{
val x = new Myclass() with Text
x.lowerCase()
x.txt()
}
}
|
Output:
geeksforgeeks
I like GeeksforGeeks
Thus, from this example we can say that the trait can even be extended while creating object.
Note: If we extend a trait first and then the abstract class then the compiler will throw an error, as that is not the correct order of trait Mixins.