当有人试图将函数用作不打算那样使用的表达式时,我如何强制编译时错误?
fun someFunctionThatReturnsNothing() { println("Doing some stuff") }
// this should give an error:
val value = someFunctionThatReturnsNothing()
我的用例是生成一个 DSL,其中 DSL 构建器和其他构建器中的子 DSL 之间可能存在名称冲突,具体取决于执行范围 - 例如:
// this is valid, calling RequestDSL.attribute(...) : Unit here,
val myRequest = request {
attribute {
name = "foo"
value = "bar"
}
}
// this is valid, calling AttributeDSLKt.attribute(...) : Attribute
val special = attribute {
name = "special"
value = "ops"
}
val myRequest = request {
extraAttribute = special
}
// this does not compile, but is confusing,
// because the compiler does not complain where the error was made
val myRequest = request {
// the user intends to call AttributeKt.attribute(...) : Attribute,
// but the compiler can only call RequestDSL.attribute(...) : Unit here
val special = attribute {
name = "special"
value = "ops"
}
// this is confusing and should already have been prevented above:
// >> Type mismatch. Required: Attribute. Found: Unit. <<
extraAttribute = special
}
如果我可以做类似RequestDSL.attribute(...) : void
的事情,甚至不允许用户attribute(...)
在 DSL 中作为表达式调用。这样可以避免这个问题。
这可以以某种方式完成吗?
我试过Nothing
了,但它只是使函数调用后所有代码都无法访问。
我也尝试过Void
,但它只是迫使我使返回可为空并返回 null 而不是在调用端给出错误。