gpt4 book ai didi

scala:如何包装子类构造函数的执行?

转载 作者:行者123 更新时间:2023-12-01 01:28:46 25 4
gpt4 key购买 nike

在 Scala 中,我有一个基类和一些子类。无需向子类添加代码或更改子类的实例化,我希望基类能够在执行子构造函数之前和之后调用一些代码。 before 很容易,因为基类构造函数在 child 之前调用,但我没有看到处理 after 情况的方法。作为一些示例代码:

class A {
// do some stuff before child constructor is called
// ...

// do some other stuff after child constructor is called
// this could be a method or inline in the constructor, doesn't matter.
}

class B extends A { // stuff happens in between }

class C extends A { // stuff happens in between }
etc

val b = new B // everything happens inside, no other method call needed

这种行为可能吗?谢谢。

最佳答案

如果你使用 Scala 2.9,你可以这样安排:

class A { 
println("Hi")
}
class B extends A with DelayedInit {
private[this] var count = 0
println("Hey")
def delayedInit(x: => Unit) {
x
count += 1
if (count==2) { println("There") }
}
}
class C extends B { println("Ho") }
class D extends C { println("Ha") }

这利用了新的 DelayedInit将延迟构造函数从当前类和所有子类发送到 delayedInit 的特征方法。不幸的是,由于没有终止信号,您只能跳过单个构造函数。所以对于 C ,我们得到:
scala> new C
Hi
Hey
Ho
There

在来自 C 的“Ho”块之后,“There”块神奇地出现了.不幸的是,如果您延长 C ,新的初始化最后发生:
scala> new D
Hi
Hey
Ho
There
Ha

(你真的不需要 A 那里...我只是把它放在那里来说明父类(super class)会发生什么。)

关于scala:如何包装子类构造函数的执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6078657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com