Kotlin DSL-返回值的推断
我正在尝试介绍以下(简化的)DSL:
fun <T> myDsl(specFn: DslSpec<T>.() -> Unit) {
val value = DslSpec<T>().apply(specFn).fn!!()
println("value is: $value")
}
class DslSpec<T> {
internal var fn: (() -> T)? = null
fun getValue(fn: () -> T) {
this.fn = fn
}
}
fun testCase() {
myDsl {
getValue {
"abc"
}
}
}
但是仅根据返回的类型getValue
( “没有足够的信息来推理t
)推断类型变量t“ )。我有点了解编译器这可能是一项非常艰巨的任务,但是认为也许已经有一些技巧可以使这样的构造工作?
I'm trying to introduce the following (simplified) DSL:
fun <T> myDsl(specFn: DslSpec<T>.() -> Unit) {
val value = DslSpec<T>().apply(specFn).fn!!()
println("value is: $value")
}
class DslSpec<T> {
internal var fn: (() -> T)? = null
fun getValue(fn: () -> T) {
this.fn = fn
}
}
fun testCase() {
myDsl {
getValue {
"abc"
}
}
}
But it fails to infer T
based just on the returned type of getValue
("Not enough information to infer type variable T"). I kind of see how it could be a very hard task to do for a compiler, but thought maybe there are already some tricks to make constructs like this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用的是Kotlin&lt; 1.6.0,您应该将
@builderInference
添加到specfn
参数:https://pl.kotl.in/__xy04j88
如果您使用的是版本&gt; = 1.6.0,则应使用注释,或者必须汇总声明及其用法使用编译器参数
- 可搭建的构建器 -
。If you're using a version of Kotlin < 1.6.0, you should add
@BuilderInference
to thespecFn
argument:https://pl.kotl.in/__xy04j88
If you're using a version >= 1.6.0, you should either use the annotation as well, or both your declarations and their usages must be compiled with the compiler argument
-Xenable-builder-inference
.