Home » Scala language

Scala Trait Mixins

Increasing the number of traits in Scala is Trait Mixins. In this tutorial on Scala Trait Mixins, we will learn about Trait Mixins in Scala.
Submitted by Shivang Yadav, on March 08, 2020

Scala | Trait Mixins

In Scala, the number of traits can be extended using a class or an abstract class. This is known as Trait Mixins. For extending, only traits, the blend of traits, class or abstract class are valid.
If the sequence of Trait Mixins is not maintained, an error is thrown by the compiler. It is used in composing a class. As multiple traits can be inherited.

Let's look at a few examples to understand the topic better,

Example 1: Extending abstract class with a trait

trait Bike { 
	def Bike() ;
} 

abstract class Speed { 
	def Speed() ;
} 

class myBike extends Speed with Bike { 
	def Bike() {	 
		println("Harley Davidson Iron 883") ;
	} 
	def Speed() {									 
		println("Max Speed : 170 KmpH") ;
	} 
} 

object myObject { 
	def main(args:Array[String]) { 
		val newbike = new myBike() ;
		newbike.Bike() ;
		newbike.Speed() ;
	} 
} 

Output

Harley Davidson Iron 883
Max Speed : 170 KmpH

Example 2: Extending abstract class without a trait

trait Bike { 
	def Bike() ;
} 

abstract class Speed{ 
	def Speed() ;
} 

class myBike extends Speed { 
	def Bike() {	 
		println("Harley Davidson Iron 883") ;
	} 
	def Speed() {	
	    
		println("Max Speed : 170 KmpH") ;
	} 
} 

object myObject { 
	def main(args:Array[String]) { 
		val newbike = new myBike() with Bike;
		newbike.Bike() ;
		newbike.Speed() ;
	} 
} 

Output

Harley Davidson Iron 883
Max Speed : 170 KmpH



Comments and Discussions!

Load comments ↻






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