Scala trait,extends,with and Unit

Category : Scala | Sub Category : Scala Programs | By Runner Dev Last updated: 2020-10-08 14:26:54 Viewed : 226


Scala trait,extends,with and Unit

 ·        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 it’s abstract

} 

trait TailWagger {

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

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

} 

trait Runner {

    def startRunning(): Unit = println("I’m 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 it’s 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
Sub-Categories
Related Articles

Leave a Comment: