×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala Trait Mixins

By IncludeHelp Last updated : October 26, 2024

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(): Unit
} 

abstract class Speed { 
  def speed(): Unit
} 

class MyBike extends Speed with Bike { 
  def bike(): Unit = {	 
    println("Harley Davidson Iron 883") 
  } 
  
  def speed(): Unit = {									 
    println("Max Speed: 170 KmpH") 
  } 
} 

object MyObject { 
  def main(args: Array[String]): Unit = { 
    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(): Unit
} 

abstract class Speed { 
  def speed(): Unit
} 

class MyBike extends Speed { 
  def bike(): Unit = {	 
    println("Harley Davidson Iron 883") 
  } 
  
  def speed(): Unit = {									 
    println("Max Speed: 170 KmpH") 
  } 
} 

object MyObject { 
  def main(args: Array[String]): Unit = { 
    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.