Kotlin DSL-返回值的推断

发布于 2025-01-30 12:47:26 字数 607 浏览 4 评论 0原文

我正在尝试介绍以下(简化的)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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撩心不撩汉 2025-02-06 12:47:26

如果您使用的是Kotlin&lt; 1.6.0,您应该将@builderInference添加到specfn参数:

fun <T> myDsl(@BuilderInference specFn: DslSpec<T>.() -> Unit) {
    ...
}

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 the specFn argument:

fun <T> myDsl(@BuilderInference specFn: DslSpec<T>.() -> Unit) {
    ...
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文