如何在Scala中重写同一类中的方法

k5hmc34c  于 2022-11-09  发布在  Scala
关注(0)|答案(2)|浏览(209)

我想知道是否有一种方法可以覆盖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")
}

基本上,我希望每次调用a()时都要计算var hello = "Hello",直到b()被调用,然后a()应该打印"Hi, how is your day going",直到c()被调用时重置,然后它应该返回执行var hello = "Hello"。有没有办法使用这个,如果没有,还有其他方法吗?我不想用条件句。先谢谢你。

bd1hkmkf

bd1hkmkf1#

因此,基本上您希望定义a()以使用动态行为。

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
  }

}
pbpqsu0x

pbpqsu0x2#

作为一个强烈不喜欢使用var s的人,我认为以下内容并不优雅,但如果vars适合您,您可以这样做:

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
  }
}

相关问题