我想知道是否有一種方法可以覆寫 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")
}
基本上,我想計算var hello = "Hello"
何時a()
被呼叫,直到b()
被呼叫,然后a()
應該列印"Hi, how is your day going"
直到它c()
被呼叫時重置,然后它應該回到執行var hello = "Hello"
。有沒有辦法使用它,如果沒有,還有其他方法嗎?我不想使用條件。提前致謝。
uj5u.com熱心網友回復:
所以,基本上你想定義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
}
}
uj5u.com熱心網友回復:
作為一個強烈不喜歡使用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
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/524170.html
標籤:斯卡拉