Monday, 21 September 2020

Scala: Traits

 

Scala do not have interface, but it support same functionality using traits. A trait in Scala can have abstract fields, class that implements this trait must provide values to these abstract fields.

 

Syntax

trait TraitName{

     ......

     ......

}

 

Example

trait SortData{

    

     def sort() = {

          .....

          .....

     }

 

}

 

Can a trait extends other trait?

Yes

 

trait StringSort extends SortData {

     .......

     .......

}

 

Can a class extend multiple traits?

Yes

 

Can a trait have concrete methods?

Yes

 

Can a trait have concrete fields?

Yes

 

Let’s implement trait with simple logger example.

 


Step 1: Define Logger trait.

trait Logger {
  def logInfo(msg: String): Unit = println(msg)
  def logWarning(msg: String): Unit = println(msg)
  def logError(msg: String): Unit = println(msg)
}

Step 2: Define ConsoleLogger and DBLogger traits.

trait ConsoleLogger extends Logger {
  override def logInfo(msg: String): Unit = {
    val date = new java.util.Date()

    println(s"$date $msg")

  }

  override def logWarning(msg: String): Unit = {
    logInfo(msg)
  }

  override def logError(msg: String): Unit = {
    logInfo(msg)
  }

}

trait DBLogger extends Logger {}

Step 3: Define a class and extend Logger trait.

class UserService extends Logger {
  def registerNewUser(id: Int, name: String) = {
    logInfo(s"user id: $id and name: $name registered successfully!!!!")
  }
}

Now you can supply any Logger trait to the UserService object and use.

 

Example 1: UserService instance with Logger trait

val userService1 = new UserService() with Logger

 

Example 2: UserService instance with ConsoleLogger trait

val userService2 = new UserService() with ConsoleLogger

 

Find the below working application.

 

TraitDemo.scala

package com.sample.app

object TraitDemo extends App {
  trait Logger {
    def logInfo(msg: String): Unit = println(msg)
    def logWarning(msg: String): Unit = println(msg)
    def logError(msg: String): Unit = println(msg)
  }

  trait ConsoleLogger extends Logger {
    override def logInfo(msg: String): Unit = {
      val date = new java.util.Date()

      println(s"$date $msg")

    }

    override def logWarning(msg: String): Unit = {
      logInfo(msg)
    }

    override def logError(msg: String): Unit = {
      logInfo(msg)
    }

  }

  trait DBLogger extends Logger {}

  class UserService extends Logger {
    def registerNewUser(id: Int, name: String) = {
      logInfo(s"user id: $id and name: $name registered successfully!!!!")
    }
  }

  val userService1 = new UserService() with Logger
  val userService2 = new UserService() with ConsoleLogger

  userService1.registerNewUser(1, "Krishna")
  userService2.registerNewUser(1, "Krishna")
}






 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment