Search code examples
scala

How to override a method in the same class in Scala


I wanted to know if theres a way to override a method within the same class in scala.

class xyz {    
def a() : Unit = {
var hello = "Hello"

}
def b() : Unit = {
//method to override the functionality of b, for example lets say I want it to just print "Hi, how is your day going" until its somehow reset and after its resett it should go back to doing var hello = "Hello"
}

}
def c() : Unit = {
//reset a to do what it was doing earlier (var hello = "Hello")
}

Basically I want to compute var hello = "Hello" whenever a() is called until b() is called and then a() should print "Hi, how is your day going" until its reset when c() is called and then it should go back to performing var hello = "Hello". Is there a way to use this, if not is there another way? I don't want to use conditionals. Thanks in advance.


Solution

  • So, basically you want to define a() to use a dynamic behaviour.

    object Behave {
    
      val helloComputeBehaviour: () => Unit =
        () => {
          // default behaviour
          var hello = "Hello"
        }
    
      val printDayGreetingBehaviour: () => Unit =
        () => {
          // behaviour after switch
          println("Hi, how is your day going")
        }
    
      var behaviour: () => Unit =
        helloComputeBehaviour
    
      def a(): Unit =
        behaviour()
    
      def b(): Unit = {
        // switch behaviour
        behaviour = printDayGreetingBehaviour
      }
    
    
      def c(): Unit = {
        // go back to default behaviour
        behaviour = helloComputeBehaviour
      }
    
    }