Page Contents
What is Scala Trait ?
Traits are similar to Java 8’s interfaces. Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters. Traits become especially useful as generic types and with abstract methods.
A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Unlike class inheritance, in which each class must inherit from just one super class, a class can mix in any number of traits.
Scala traits are a great feature of the language. You can use them just like a Java interface, and you can also use them like abstract classes that have real methods. Scala classes can also extend and “mix in” multiple traits.
A trait definition looks just like a class definition except that it uses the keyword trait. The following is the basic example syntax of trait.
Defining a Trait
trait Iterator[A] { def hasNext: Boolean def next(): A }
Using trait
extends
keyword is used to extend a trait. Then implement any abstract members of the trait using the override
keyword.
trait Iterator[A] { def hasNext: Boolean def next(): A } class IntIterator(to: Int) extends Iterator[Int] { private var current = 0 override def hasNext: Boolean = current < to override def next(): Int = { if (hasNext) { val t = current current += 1 t } else 0 } } object MyTest extends App { val iterator = new IntIterator(10) while(iterator.hasNext){ println(iterator.next()) } }
Save the above program in MyTest.scala. Compile and run as mentioned below
scalac MyTest.scala scala MyTest
Output
0 1 2 3 4 5 6 7 8 9
Lets take another simple example
We have a Trait Animal and there are two concrete classes that extends the Trait.
The trait Animal has an abstract field name that gets implemented by Cat and Dog in their constructors.
Animal also overrides the toString() method of Super class Any.
Example
trait Animal { val name: String override def toString()= { name } } class Cat(val name: String) extends Animal class Dog(val name: String) extends Animal object MyTest extends App { val dog = new Dog("Dog") val cat = new Cat("Cat") println(dog) println(dog) }
Save the above program in MyTest.scala. The following commands are used to compile and execute this program.
scalac MyTest.scala scala MyTest
Output
Dog Cat
Example – Mixing classes and traits.
trait Logger{ def log(msg: String){} } trait ConsoleLogger extends Logger{ override def log(msg: String) { println(msg) } } class Account { protected var balance = 0.0 } class SavingsAccount extends Account with ConsoleLogger{ def withdraw(amount: Double) { if (amount > balance) log("Insufficient funds") else balance -= amount } } object MyTest extends App { val acct1 = new SavingsAccount acct1.withdraw(100) }
Save the above program in MyTest.scala. The following commands are used to compile and execute this program.
scalac MyTest.scala scala MyTest
Output
Insufficient funds
References : https://docs.scala-lang.org/tour/traits.html