gradle / kotlin-dsl-samples

Samples builds using the Gradle Kotlin DSL
https://gradle.org/kotlin/
Other
3.71k stars 433 forks source link

KT-26983 - Kotlin compiler smart casting confused by var with same name in class member #1115

Open SimonLammer opened 6 years ago

SimonLammer commented 6 years ago

Buildscript:

open class CustomTask : DefaultTask() {
  var dir = File(".")

  @TaskAction
  fun action() {
    println("CustomTask.dir: ${dir.absolutePath}")
  }
}
tasks.create<CustomTask>("debug") {
  //dir = File(".gradle") // Script compilation fails if I uncomment this line
}

tasks.create("traverseDir") {
  doLast {
    traverseDir(File("gradle/wrapper/gradle-wrapper.jar"))
  }
}
fun traverseDir(file: File) {
  var dir: File? = file.parentFile
  while (dir != null) {
    println(dir)

    dir = dir.parentFile
  }
}

Expected Behavior

Build should continue to succeed when I configure the custom task.

Current Behavior

Buildscript fails to compile:

> Configure project :
e: /home/.../gradle-kotlin_dsl-smart_cast_error/build.gradle.kts:32:11: Smart cast to 'File' is impossible, because 'dir' is a local variable that is captured by a changing closure

FAILURE: Build failed with an exception.

* Where:
Build file '/home/.../gradle-kotlin_dsl-smart_cast_error/build.gradle.kts' line: 32

* What went wrong:
Script compilation error:

  Line 32:     dir = dir.parentFile
                     ^ Smart cast to 'File' is impossible, because 'dir' is a local variable that is captured by a changing closure

1 error

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 0s

Your Environment

Output of ./gradlew --version:

------------------------------------------------------------
Gradle 4.10
------------------------------------------------------------

Build time:   2018-08-27 18:35:06 UTC
Revision:     ee3751ed9f2034effc1f0072c2b2ee74b5dce67d

Kotlin DSL:   1.0-rc-3
Kotlin:       1.2.60
Groovy:       2.4.15
Ant:          Apache Ant(TM) version 1.9.11 compiled on March 23 2018
JVM:          1.8.0_181 (Oracle Corporation 25.181-b13)
OS:           Linux 4.15.0-33-generic amd64

Additional

I have asked this on stackoverflow a few days ago: https://stackoverflow.com/questions/52302399/why-does-this-gradle-buildscript-kotlin-dsl-fail-to-compile-when-i-introduce On the jetbrains kotlin issue tracker too: https://youtrack.jetbrains.com/issue/KT-26983

eskatos commented 6 years ago

It looks like the Kotlin compiler is confused by dir being ambiguously resolved. @SimonLammer could you please open an issue on JetBrains Youtrack https://youtrack.jetbrains.com/issues/KT and link it from here?

SimonLammer commented 6 years ago

@eskatos ok. https://youtrack.jetbrains.com/issue/KT-26983

eskatos commented 6 years ago

Thank you @SimonLammer