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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.