【问题标题】:How to convert sourceSets from a project to kotlin kts如何将 sourceSets 从项目转换为 kotlin kts
【发布时间】:2025-12-30 08:50:11
【问题描述】:

我有一个多模块 gradle 项目。我正在将所有 build.gradle 配置文件转换为 Kotlin kts。

但我找不到如何将下面的代码转换为 kotlin kts。

我试图在 kts 中放置 groovy 代码并检查文档,但我找不到任何东西。

    testCompile project(":entities").sourceSets.test.output

【问题讨论】:

    标签: gradle-kotlin-dsl


    【解决方案1】:

    经过一番调查,我发现这方面的语法最近发生了变化。

    我尝试了一些变体,发现:

    dependencies {
      testImplementation(project(":entities").sourceSets["test"].output)
    }
    

    结果

    testImplementation(project(":entities").sourceSets["test"].output)
                                         ^ Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
                                                            public val Project.sourceSets: SourceSetContainer defined in org.gradle.kotlin.dsl
    

    但只要启用了 Java 插件,以下内容就可以正常工作:

    val entityTests: SourceSetOutput = project(":entities").sourceSets["test"].output
    
    dependencies {
      testImplementation(entityTests)
    }
    

    【讨论】:

    • 对我来说它不起作用,我仍然得到Unresolved reference: sourceSets。但是当我在sourceSets 之前添加java 时,它可以工作,但是,我得到了以前没有发生的构建错误。
    • 项目的 sourceSets 属性只有在启用 Java 插件时才会被激活。见docs.gradle.org/5.4/dsl/org.gradle.api.Project.html#N159F7。我会更新我的答案以包括这个。如果您提供更多信息,我或许可以帮助解决构建错误。
    • 仅当 val 未在依赖项块中声明时才有效(仅供参考)