Scala trait,extends,with and Unit

Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2020-10-08 08:56:54 Viewed : 545


Scala trait,extends,with and Unit

In Scala, traits, extends, with, and Unit are all important concepts related to defining classes, inheritance, and function return types. Let is explore each of them:

1. Trait:

A trait in Scala is similar to an interface in other programming languages. It defines a set of abstract methods and fields that can be mixed into classes. Traits can be used to achieve multiple inheritance-like behavior in Scala.

Here is an example of a trait called Logger:

scala
trait Logger { def log(message: String): Unit }

Classes can then mix in the Logger trait to inherit its behavior:

scala
class ConsoleLogger extends Logger { def log(message: String): Unit = { println(s"Logging: $message") } }

2. extends:

The extends keyword is used to indicate that a class is inheriting from another class or a trait. In the example above, ConsoleLogger extends the Logger trait.

3. with:

In Scala, you can mix multiple traits into a class using the with keyword. This allows you to inherit behavior from multiple sources. For example:

scala
trait Debug { def debug(message: String): Unit = { println(s"Debugging: $message") } } class ConsoleLogger extends Logger with Debug { def log(message: String): Unit = { println(s"Logging: $message") } }

In this example, ConsoleLogger mixes in both the Logger and Debug traits using the with keyword.

4. Unit:

In Scala, Unit is similar to void in some other languages, and it represents the absence of a meaningful value. Functions in Scala can return Unit when they dont have a meaningful result to return. For example:

scala
def printMessage(message: String): Unit = { println(message) }

In this case, the printMessage function prints the provided message but doesnt return any meaningful value, so its return type is Unit.

Here is an example of how you can use these concepts together:

scala
trait Logger { def log(message: String): Unit } trait Debug { def debug(message: String): Unit = { println(s"Debugging: $message") } } class ConsoleLogger extends Logger with Debug { def log(message: String): Unit = { println(s"Logging: $message") } } object Main extends App { val logger = new ConsoleLogger() logger.log("This is a log message") logger.debug("This is a debug message") }

In this example, we have a ConsoleLogger class that extends the Logger trait and mixes in the Debug trait. The log and debug methods print messages, and their return type is Unit since they dont return meaningful values. The Main object demonstrates how to use this logger.

 ·        trait

A trait is like an interface with a partial implementation. In scala, trait is a   collection of abstract and non-abstract methods.

 ·        Extends Keyword

We inherit from can either be a trait or a class, using the extends keyword.

trait  X

class Y

            class A extends X

            class B extends Y 

·        with keyword

We can define  inherited traits (and only traits) using the with keyword. 

class A extends Y with X 

·        scala.Unit

Unit is a subtype of scala.AnyVal. There is only one value of type Unit, (), and it is not represented by any object in the underlying runtime system. A method with return type Unit is analogous to a Java method which is declared void 

Way of declaring the traits and Unit: 

trait Speaker {

    def speak(): String  // has no body, so its abstract

} 

trait TailWagger {

    def startTail(): Unit = println("tail is wagging")

    def stopTail(): Unit = println("tail is stopped")

} 

trait Runner {

    def startRunning(): Unit = println("I am running")

    def stopRunning(): Unit = println("Stopped running")

} 

Example:

Following example illustrates about Scala for loop and  Yield

Save the file as −  ScalaTraitEx.scala. 

ScalaTraitEx.scala 

package runnerdev

 trait TestReader {

  def disply()

} 

class Test extends TestReader {

  def disply() {

    println("called displayed method")

  }

} 

object ScalaTraitEx {

  def main(args: Array[String]) {

    var test = new Test()

    test.disply()

  }

compile and run the above example as follows 

scala> scalac ScalaTraitEx.scala

scala> scala ScalaTraitEx

 Ouput:

called displayed method


  

Example 2:

Following example illustrates about Scala for loop and  Yield

Save the file as −  ScalaTraitEx2.scala. 

 ScalaTraitEx2.scala

package runnerdev 

trait Speaker {

  def speak(): String // has no body, so its abstract

  def show() { // Non-abstract method

    println("This is show method")

  }

}

trait TailWagger {

  def startTail(): Unit = println("tail is wagging")

  def stopTail(): Unit = println("tail is stopped")

}

 // here, with is a keyword to extend multiple traits

class TestOne extends Speaker with TailWagger {

  def disply() {

    println("calling disply method")

  } 

  def speak(): String = {

    return "calling speak method" 

  }

} 

object ScalaTraitEx2 {

  def main(args: Array[String]) {

    var test = new TestOne()

    test.disply()

    var str = test.speak()

    println(str)

    test.show()

    test.startTail()

    test.stopTail()

  }

 

Output:

calling disply method

calling speak method

This is show method

tail is wagging

tail is stopped

Search
Related Articles

Leave a Comment: