Henrique Rocha
Henrique Rocha

Reputation: 149

Gradle Kotlin DSL can't find java.io package

I'm trying to convert the build.gradle file of an Android app to a Kotlin DSL. This file has a function like this:

def getLastCommitHash() {
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'rev-parse', '--short', 'HEAD'
        standardOutput = stdout
    }
    return stdout.toString().trim()
}

which I converted to this:

fun getLastCommitHash() {
    val stdout = ByteArrayOutputStream()
    exec {
        commandLine("git", "rev-parse", "--short", "HEAD")
        standardOutput = stdout
    }
    return stdout.toString().trim()
}

I get an Unresolved reference: ByteArrayOutputStream error and applying the import which changes it to java.io.ByteArrayOutputStream() shows an Unresolved reference: io error.

Is there something I'm doing wrong? Thanks in advance.

Upvotes: 13

Views: 3410

Answers (4)

Chriki
Chriki

Reputation: 16338

Importing from java.io works when doing it before the plugins block. I could successfully run builds for both Gradle 7.3.2 and 6.9.2 with the following build.gradle.kts:

import java.io.ByteArrayOutputStream

plugins {
    `java-library`
}

println(ByteArrayOutputStream::class)

If you escape the full package name, then you can also make it work without importing the class (tested as above):

plugins {
    `java-library`
}

println(`java.security`.MessageDigest::class)

Upvotes: 10

sschrass
sschrass

Reputation: 7156

My observation:

  • close project
  • delete .idea and .gradle folders
  • open project by selecting root-build.gradle.kts with "open as project"

did help.

Upvotes: 2

estn
estn

Reputation: 1203

I had this issue in backend project in intellij idea, I added this import at the top of build.gradle file:

import java.io.ByteArrayOutputStream

And now it works.

Upvotes: 6

Henrique Rocha
Henrique Rocha

Reputation: 149

This was an issue with Android Studio 3.5.6. After upgrading to Android Studio 3.6 everything is working.

Upvotes: 1

Related Questions