Home > other >  How to override a method in the same class in Scala
How to override a method in the same class in Scala

Time:11-01

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.

CodePudding user response:

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
  }

}

CodePudding user response:

As someone who strongly prefers not to use vars, I do not think the following is elegant, but if vars are your cup of tea, you could do something like this:

class xyz {

  private val resetHello: () => Unit = () => {
    // set hello ...
  }

  private val printHi: () => Unit = () => {
    // print "Hi..."
  }
  
  // variable holding the current behavior of def a()
  private var behaviorOfA: () => Unit = resetHello

  def a(): Unit = {
    // execute the current behavior
    behaviorOfA()
  }

  def b(): Unit = {
    behaviorOfA = printHi
  }

  def c(): Unit = {
    behaviorOfA = resetHello
  }
}
  • Related