Unresolved reference: launch - gradle

Trying to run some examples for Kotlin coroutines, but can't build my project. I'm using the latest gradle release - 4.1
Any suggestions what to check/fix?
Here is build.gradle
buildscript {
ext.kotlin_version = '1.1.4-3'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'kotlin'
apply plugin: 'application'
kotlin {
repositories {
jcenter()
}
experimental {
coroutines 'enable'
}
dependencies {
compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.18"
}
}
and the main.kt
fun main(args: Array<String>) {
launch (CommonPool) {
delay(1000L)
println("World!")
}
println("Hello, ")
Thread.sleep(2000L)
}
when I run gradle compileKotlin I get the following
e: /Users/philippgrigoryev/projects/kotlin-coroutines/src/main/kotlin/main.kt: (2, 5): Unresolved reference: launch
e: /Users/philippgrigoryev/projects/kotlin-coroutines/src/main/kotlin/main.kt: (2, 13): Unresolved reference: CommonPool
e: /Users/philippgrigoryev/projects/kotlin-coroutines/src/main/kotlin/main.kt: (3, 9): Unresolved reference: delay`

Launch isn't used anymore directly. The Kotlin documentation suggests using:
fun main() {
GlobalScope.launch { // launch a new coroutine in background and continue
delay(1000L)
println("World!")
}
println("Hello,") // main thread continues here immediately
runBlocking { // but this expression blocks the main thread
delay(2000L) // ... while we delay for 2 seconds to keep JVM alive
}
}

If you are using Coroutines 1.0+, the import is no longer
import kotlinx.coroutines.experimental.*
but
import kotlinx.coroutines.launch
You would need the following in the dependencies closure of your build.gradle (for Coroutines 1.0.1):
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.1'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.1"

Like already answered in the comments, the import is missing for the kotlinx.coroutines.experimental.* package. You can have a look at my examples at GitHub if you like.
import kotlinx.coroutines.experimental.*
fun main(args: Array<String>) {
launch(CommonPool) {
delay(1000)
LOG.debug("Hello from coroutine")
}
}

This confused me for a while because the tutorial I am doing shows it used directly... I think they have changed how it is used from a previous version.
I think the trick is that you can only call launch() within a Coroutine scope.
So this does not work:
fun main() {
launch() // not called within coroutine scope
}
Where this will work:
fun main() {
runBlocking {
launch() // called within coroutine scope
}
}
code snippit example

Try this way,
//add this lines to gradle
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$rootProject.kotlinx_coroutines"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$rootProject.kotlinx_coroutines"
class xyz{
private val job = Job()
private val coroutinesScope: CoroutineScope = CoroutineScope(job + Dispatchers.IO)
....
. ...
coroutinesScope.launch {
// task to do
Timber.d("Delete Firebase Instance ID")
}
// clear the job
job.cancel()
}

I am using
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1"
Instead of launch, GlobalScope.launch works.
Given below is the imports:-
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

I met this issue while using kotlinx-corountine-core library, here is my gradle,
buildscript {
ext.kotlin_version = '1.5.21'
ext.kotlin_coroutines_version = '1.3.9'
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:3.6.0"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.tencent.mm:AndResGuard-gradle-plugin:1.2.20'
}
}
// .....
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar", '*.aar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$kotlin_coroutines_version"
}
Then the launch and many other references from kotlin coroutines can't be found. Here is my procedure to solve this problem,
First, find the final dependences under Android Studio. I'm surprised to find that the final kotlin coroutine library was 1.5.0, AND IT SHOULD BE EMPTY!
1.3.9 is also included, but 1.5.0 is greater. So, 1.5.0 will be used finally.
Then I tried to find out the project dependencies by the following command,
>gradlew :app:dependencies
where 'aap' is the project module name.
Then I found it's lifecycle-viewmodel-ktx using it.
So, I tried to upgrade the library to a greater version, 1.6.0. Then, I found it's not empty now and every references work again.
So, to solve it, you need,
find which version of kotlin coroutines core library you are using in your project
investigate what's going on in that library, is that 1.5.0 or empty?
find who introduced this version
try upgrade to a newer version

try this
CoroutineScope(coroutineContext).launch {
}

Related

buildSrc Version script object not being added root buildScript or any project context

i have a simple buildSrc configuration for dependency versions
a buildSrc/gradle.build.kts:
repositories {
jcenter()
}
plugins {
`kotlin-dsl`
}
dependencies {
implementation(kotlin("script-runtime"))
}
I would like to point out that my kotlin script wouldnt work at all without the script-runtime dependency and I have never seen any documentation saying its required but once i added it an error went away:
"No script runtime was found in the classpath: class 'kotlin.script.templates.standard.ScriptTemplateWithArgs' not found. Please add kotlin-script-runtime.jar to the module dependencies."
Then i have a simple object script buildSrc/src/main/java/Versions.kts
object Versions {
val kotlin = "1.3.61"
val kotlinFrontentPlugin = "0.0.45"
}
Doesnt get much simpler.
Then in my root project i have:
build.gradle.kts:
buildscript {
repositories {
google()
mavenCentral()
jcenter()
maven("https://plugins.gradle.org/m2/")
maven("https://dl.bintray.com/kotlin/kotlin-eap")
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}")
classpath("org.jetbrains.kotlin:kotlin-frontend-plugin:${Versions.kotlinFrontendPlugin}")
}
}
This is all just straight up copy and paste. but all i can get is:
Line 12: classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}")
^ Unresolved reference: kotlin
Line 13: classpath("org.jetbrains.kotlin:kotlin-frontend-plugin:${Versions.kotlinFrontendPlugin}")
^ Unresolved reference: kotlinFrontendPlugin
Does buildSrc just no longer work in builds anymore or is there yet some other undocumented setting or action i need to take?
Found the issue. I accidentally named my object as a script
Versions.kts when it needed to be Versions.kt

How to add a dependency to build.gradle.kts for kotlin-multiplatform (kotlin 1.3.50)?

I started a new project with kotlin-multiplatform to create a library usable on iOS and Android using this tutorial :
https://play.kotlinlang.org/hands-on/Targeting%20iOS%20and%20Android%20with%20Kotlin%20Multiplatform/01_Introduction
It seems to work fine but I wanted to add the Serialization library mentioned at the end of the tutorial (https://github.com/Kotlin/kotlinx.serialization) and I can't make it work.
The setup guide in the library is not in Kotlin DSL so I tried different things to adapt the code but without success. Here is my project gradle :
buildscript {
ext.kotlin_version = '1.3.50'
repositories {
google()
jcenter()
maven { url "https://kotlin.bintray.com/kotlinx" }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
And now my build.gradle.kts
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
plugins {
kotlin("multiplatform")
kotlin("plugin.serialization")
}
kotlin {
//select iOS target platform depending on the Xcode environment variables
val iOSTarget: (String, KotlinNativeTarget.() -> Unit) -> KotlinNativeTarget =
if (System.getenv("SDK_NAME")?.startsWith("iphoneos") == true)
::iosArm64
else
::iosX64
iOSTarget("ios") {
binaries {
framework {
baseName = "SharedCode"
}
}
}
jvm("android")
sourceSets["commonMain"].dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib-common")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:0.13.0")
}
sourceSets["androidMain"].dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.13.0")
}
sourceSets["iosMain"].dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime-native:0.13.0")
}
}
val packForXcode by tasks.creating(Sync::class) {
val targetDir = File(buildDir, "xcode-frameworks")
/// selecting the right configuration for the iOS
/// framework depending on the environment
/// variables set by Xcode build
val mode = System.getenv("CONFIGURATION") ?: "DEBUG"
val framework = kotlin.targets
.getByName<KotlinNativeTarget>("ios")
.binaries.getFramework(mode)
inputs.property("mode", mode)
dependsOn(framework.linkTask)
from({ framework.outputDirectory })
into(targetDir)
/// generate a helpful ./gradlew wrapper with embedded Java path
doLast {
val gradlew = File(targetDir, "gradlew")
gradlew.writeText("#!/bin/bash\n"
+ "export 'JAVA_HOME=${System.getProperty("java.home")}'\n"
+ "cd '${rootProject.rootDir}'\n"
+ "./gradlew \$#\n")
gradlew.setExecutable(true)
}
}
tasks.getByName("build").dependsOn(packForXcode)
I have no errors but I cannot use the library in my code.
Can someone please explain how to integrate this dependency or any dependency with this setup ? What do I do wrong ?
Note : I'm using Android Studio 3.5.1, Gradle 5.4.1, Kotlin 1.3.50.
Ok, so I found the issue.. just the version of the library.. 0.13.0 not 0.14.0. No error is thrown when you sync a wrong library version. I hope this post helps someone anyway.

How to add a dependency in a multiplatform kotlin / native intellij project?

I have the following build.gradle configuration:
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.3.41'
}
repositories {
mavenCentral()
}
kotlin {
linuxX64("linux") {
binaries {
executable {
entryPoint = 'sample.main'
runTask?.args('')
}
}
}
sourceSets {
linuxMain {
dependencies {
api("org.http4k:http4k-core:3.183.0")
}
}
linuxTest {
}
}
}
And the following source file src/linuxMain/kotlin/sample/SampleLinux.kt :
package sample
fun hello(): String = "Hello, Kotlin/Native!"
fun main() {
println(hello())
}
How to add a external library in order to be able to use autocomplete in imports for the library org.http4k:http4k-core:3.183.0?
As you can see, I tried to add the line api("org.http4k:http4k-core:3.183.0") in linuxMain dependencies, but although intellij show the library in External Libraries section, I cannot work with the packages neither classes of http4k in SampleLinux.kt file: any org.http4k..... import attempt is not recognized and generates compilation error.
After a quick look, I am almost sure that http4k is JVM-only library, at least for now. According to this issue, they are still waiting for Native to grow. If you are interested, it would be nice if one can ask the library maintainers again. As far as K/N has grown a lot by the last year, maybe they change their mind.

How do I use the native JUnit 5 support in Gradle with the Kotlin DSL?

I want to use the built-in JUnit 5 with the Gradle Kotlin DSL, because during build I get this warning:
WARNING: The junit-platform-gradle-plugin is deprecated and will be discontinued in JUnit Platform 1.3.
Please use Gradle's native support for running tests on the JUnit Platform (requires Gradle 4.6 or higher):
https://junit.org/junit5/docs/current/user-guide/#running-tests-build-gradle
That links tells me to put
test {
useJUnitPlatform()
}
in my build.gradle, but what is the syntax for build.gradle.kts?
My current build file is
import org.gradle.api.plugins.ExtensionAware
import org.junit.platform.gradle.plugin.FiltersExtension
import org.junit.platform.gradle.plugin.EnginesExtension
import org.junit.platform.gradle.plugin.JUnitPlatformExtension
group = "com.example"
version = "0.0"
// JUnit 5
buildscript {
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath("org.junit.platform:junit-platform-gradle-plugin:1.2.0")
}
}
apply {
plugin("org.junit.platform.gradle.plugin")
}
// Kotlin configuration.
plugins {
val kotlinVersion = "1.2.41"
application
kotlin("jvm") version kotlinVersion
java // Required by at least JUnit.
// Plugin which checks for dependency updates with help/dependencyUpdates task.
id("com.github.ben-manes.versions") version "0.17.0"
// Plugin which can update Gradle dependencies, use help/useLatestVersions
id("se.patrikerdes.use-latest-versions") version "0.2.1"
}
application {
mainClassName = "com.example.HelloWorld"
}
dependencies {
compile(kotlin("stdlib"))
// To "prevent strange errors".
compile(kotlin("reflect"))
// Kotlin reflection.
compile(kotlin("test"))
compile(kotlin("test-junit"))
// JUnit 5
testImplementation("org.junit.jupiter:junit-jupiter-api:5.2.0")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.2.0")
testRuntime("org.junit.platform:junit-platform-console:1.2.0")
// Kotlintest
testCompile("io.kotlintest:kotlintest-core:3.1.0-RC2")
testCompile("io.kotlintest:kotlintest-assertions:3.1.0-RC2")
testCompile("io.kotlintest:kotlintest-runner-junit5:3.1.0-RC2")
}
repositories {
mavenCentral()
mavenLocal()
jcenter()
}
(The following is some blabla because this question 'contains mostly code').
I tried to find documentation on how to customize tasks in the Kotlin DSL, but I couldn't find any. In normal Groovy you can just write the name of the task and then change things in the block, but the Kotlin DSL doesn't recognise the task as such, unresolved reference.
Also, this question is related but asks for creating of new tasks, instead of customize existing tasks: How do I overwrite a task in gradle kotlin-dsl
Here is a solution for normal Gradle.
[Edit april 2019] As Pedro has found, three months after I asked this question Gradle actually created a user guide for the Kotlin DSL which can be visited at https://docs.gradle.org/current/userguide/kotlin_dsl.html
They also added a migration guide from Groovy to Kotlin at https://guides.gradle.org/migrating-build-logic-from-groovy-to-kotlin/
Answer:
The syntax you ask for is
tasks.test {
// Use the built-in JUnit support of Gradle.
useJUnitPlatform()
}
which I figured out from this example file from the Kotlin DSL GitHub, or you can use
tasks.withType<Test> {
useJUnitPlatform()
}
which is used in the this official userguide which was created a couple of months after this answer was written (thanks to Pedro's answer for noting this).
But in any case you actually are still using the buildscript block, which is a bit deprecated itself, use the new plugins DSL instead (docs). New build.gradle.kts becomes
group = "com.example"
version = "0.0"
plugins {
val kotlinVersion = "1.2.41"
application
kotlin("jvm") version kotlinVersion
java // Required by at least JUnit.
// Plugin which checks for dependency updates with help/dependencyUpdates task.
id("com.github.ben-manes.versions") version "0.17.0"
// Plugin which can update Gradle dependencies, use help/useLatestVersions
id("se.patrikerdes.use-latest-versions") version "0.2.1"
}
application {
mainClassName = "com.example.HelloWorld"
}
dependencies {
compile(kotlin("stdlib"))
// To "prevent strange errors".
compile(kotlin("reflect"))
// Kotlin reflection.
compile(kotlin("test"))
compile(kotlin("test-junit"))
// JUnit 5
testImplementation("org.junit.jupiter:junit-jupiter-api:5.2.0")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.2.0")
testRuntime("org.junit.platform:junit-platform-console:1.2.0")
// Kotlintest
testCompile("io.kotlintest:kotlintest-core:3.1.0-RC2")
testCompile("io.kotlintest:kotlintest-assertions:3.1.0-RC2")
testCompile("io.kotlintest:kotlintest-runner-junit5:3.1.0-RC2")
}
repositories {
mavenCentral()
mavenLocal()
jcenter()
}
tasks {
// Use the native JUnit support of Gradle.
"test"(Test::class) {
useJUnitPlatform()
}
}
(Since the Gradle Kotlin DSL has almost no documentation at all except a few (undocumented) example files on GitHub, I'm documenting a few common examples here.)
(Complete example project at GitHub, self-promotion...)
Adding on top of accepted answer, it is also possible to use typed task configuration like:
tasks.withType<Test> {
useJUnitPlatform()
}
Update:
Gradle docs for reference here. Specifically Example 19 which has:
tasks.withType<JavaCompile> {
options.isWarnings = true
// ...
}
this worked for me till now...
plugins {
kotlin("jvm") version "1.7.10"
}
group = "org.example"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
testImplementation(kotlin("test"))
testImplementation("org.junit.jupiter:junit-jupiter:5.9.0")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.0")
}
tasks.test {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}

Kotlin and Gradle - Reading from stdio

I am trying to execute my Kotlin class using the command:
./gradlew -q run < src/main/kotlin/samples/input.txt
Here is my HelloWorld.kt class:
package samples
fun main(args: Array<String>) {
println("Hello, world!")
val lineRead = readLine()
println(lineRead)
}
Here is my build.gradle.kts:
plugins {
kotlin("jvm")
application
}
application {
mainClassName = "samples.HelloWorldKt"
}
dependencies {
compile(kotlin("stdlib"))
}
repositories {
jcenter()
}
The code executes, but the data contained inside the input.txt file is not displayed. Here is the output I get:
Hello, world!
null
I want to be able to execute the gradlew command above and the input.txt stream be redirected to stdio. I can easily do that in C++. Once I compile my .cpp file, I can run:
./my_code < input.txt
and it executes as expected.
How can I achieve the same thing with Kotlin and Gradle?
Update: Based on this answer, I've tried adding this to build.gradle.kts but it is not a valid syntax:
AjahnCharles suggestion about run { standardInput = System.in } is correct, but to port it to kotlin-dsl you need a different syntax.
run in this case is the task name and you configure existing task of application plugin.
To configure existing task in kotlin-dsl you should use one of this ways:
val run by tasks.getting(JavaExec::class) {
standardInput = System.`in`
}
or
val run: JavaExec by tasks
run.standardInput = System.`in`
The upcoming version of Gradle 4.3 should provide API for plugin writers to read user input.
The reason of difference between of Groovy and Kotlin in this case because Groovy uses dynamic types, but in Kotlin you must specify task type to have autocompletion and just to compile config script
I finally settled on this (Gradle 7.1.1):
plugins {
application
}
tasks.getByName("run", JavaExec::class) {
standardInput = System.`in`
}
I don't know enough Kotlin yet to judge whether this is equivalent to https://stackoverflow.com/a/46662535/253921.
Almost, but this doesn't work :'(
In Theory
My understanding: < input.txt sets the standard input for the gradlew process, but by default this is not forwarded to your program.
You want to add this to your build.gradle.kts:
run {
standardInput = System.`in`
}
Sources:
https://discuss.gradle.org/t/why-doesnt-system-in-read-block-when-im-using-gradle/3308/2
https://discuss.gradle.org/t/how-can-i-execute-a-java-application-that-asks-for-user-input/3264
In Practice
These build configs look about the same to me, yet Groovy works and Kotlin doesn't. I'm starting to think that the Gradle Kotlin DSL doesn't support the standardInput term yet :/
Here's my working Groovy version if that's any help:
apply plugin: 'kotlin'
apply plugin: 'application'
buildscript {
ext.kotlin_version = '1.1.4'
repositories {
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
repositories {
jcenter()
}
dependencies {
// api => exported to consumers (found on their compile classpath)
// implementation => used internally (not exposed to consumers)
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
mainClassName = "samples.HelloWorldKt"
run {
standardInput = System.in
}

Resources