Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

What are traits in Scala?

Dian Us Suqlain

A trait is a concept in Object-Oriented Programming (OOP) that can expand the functionality of a class using a set of methods.

Traits are identical to Java interfaces, except in Scala they cannot be instantiated and have no arguments or parameters.

In the Scala programming language, you can inherit (extend) them by using classes and objects.

In Scala, traits are a set of functionalities that includes both abstract and non-abstract methods, as well as fields such as a parameter. This means that you can either define a trait with complete abstraction, or one with no abstraction at all.

Syntax

In Scala, writing a trait is fairly straightforward: it is defined by the keyword trait, then followed by the name of the trait.

trait TraitExample {
    // Variables
    // Methods
}

Key points

  • Traits don’t include any constructor parameters
  • If a class has to use a trait, then it is only accessible by keyword extend
  • Traits support multi-inheritance

Abstract trait

If a class extends a trait but does not implement its members, it is referred to as abstract.

In the example trait below, note how the abstract class TraitAbstract extends ExampleTrait but doesn’t implement the method inside it (i.e., print()).

trait ExampleTrait{  
    def print()
}  
  
abstract class TraitAbstract extends ExampleTrait {
   def printTrait(): Unit = {  
       println("Hello, this is an Abstract Trait Example")  
   }  
} 

Non-abstract trait

When implementing a non-abstract trait, we must observe the following points:

  • We can add a trait to an object instance in a non-abstract trait

  • We can also directly add a trait to a class’s object without inheriting the trait from the class

  • We can implement a trait using the with keyword in the object instance

class MyClass { }

trait MyTrait {
	println("This is a trait");
}

object Main {
	def main(args: Array[String]) : Unit = {
    val obj = new MyClass with MyTrait;
	
	}
}
Non-abstract Trait

In the above example, we implement a trait MyTrait within the object instance of Main using with keyword in line 9, since non-abstract traits support the addition of a trait to an object instance.

RELATED TAGS

scala

CONTRIBUTOR

Dian Us Suqlain
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring