有没有办法强制一个 kotlin 函数只能在另一个函数的上下文中是 运行?

Is there a way to enforce that a kotlin function can be run only in the context of another function?

我正在尝试回复这个答案 我的想法是创建一个函数来实现一些验证并允许验证函数仅在验证函数的上下文中调用。可能吗?这是我当前的代码:

interface MathThing {

    fun mathFunction(x: Int)
}

fun validationContext(x: Int, block: (Int) -> Unit){
    require(x > 0)
    block(x)
}

fun main() {

    val o = object : MathThing {
        override fun mathFunction(x: Int) {
            println(x)
        }
    }

    validationContext(-1, o::mathFunction)

}

您的代码中的问题是您实际上并未在块中调用 o::mathFunction。你宁愿只是参考它。在这种情况下,它只是空操作。

您可以通过将 mathFunction 作为参数传递或在块内显式调用它来修复它:

validateContext(1) {
    o.mathFunction(it)
}
// ok. => 1

validateContext(1, o::mathFunction)
// ok. => 1

validateContext(-1, o::mathFunction)
// validation error

更新

简短的回答是 'no'。你不能轻易地限制它,除非你的语言有动态绑定的执行上下文。

您可以尝试抛出错误、分析堆栈跟踪并确定所需的上下文函数是否在调用堆栈中。但这会非常缓慢和痛苦。

我会做这样的事情,以确保函数始终得到验证

val o = object : MathThing {
    override fun mathFunction(x: Int) = validateContext(x) {
        println(it)
    }
}