Karlo Lozovina
09/13/2021, 6:36 PMBase
, Is there a way to run some code before and after every method call on Base's subclasses?andylamax
09/14/2021, 12:23 AMopen class Base{
fun mustRun() {
// . . .
}
inline fun <T> withMustRun(block: ()->T) {
mustRun()
val res = block()
mustRun()
return res;
}
}
and then you can now do things like
class Child: Base() {
fun methodOne() = withMustRun {
// doStuff here
}
}
Wrapping every method using withMustRun
will run mustRun
before and after your code blockephemient
09/14/2021, 5:33 AMopen class Base {
/* final */ fun foo() {
println("before foo()")
doFoo()
println("after foo()")
}
protected abstract fun doFoo()
}
class Child : Base() {
override fun doFoo() { ... }
}
this prevents unrelated code from invoking doFoo
directly, only foo
which wraps itStephan Schroeder
09/14/2021, 7:12 AMephemient
09/14/2021, 7:31 AMKarlo Lozovina
09/14/2021, 8:08 AMMatteo Mirk
09/14/2021, 9:00 AMStephan Schroeder
09/14/2021, 1:17 PMwithMustRun
will just have access to whatever parameters the invoking functions has without those parameters being explicitly provided to it. So
class SubBase: Base() {
fun methodOne(a: Int) = withMustRun {
// doStuff here with a
}
fun methodTwo(s1: String, s2: String) = withMustRun {
// doStuff here with s1 & s2
}
}
will both work. But since you you have to use withMustRun
explicitly anyway, I'd declare it and mustRun
top-level and not as part of Base
.Karlo Lozovina
09/14/2021, 3:07 PM