3

I`m testing coroutine example code on IntelliJ IDEA. But I cannot import library which needs for coroutine.

I created project as Kotlin - "JVM | IDEA". I tried simple print hello world code and succeesfully done. But coroutine example don`t even execute.

import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock


fun main()
{
    runBlocking {

      var counter = 0
      val lock = Mutex()  

      val coroutines = List(3) {
        launch {
          repeat(1_000) {
            lock.withLock {
              counter++
            }
          }
        }
      }

      coroutines.forEach { it.join() }

      println("Final counter: $counter")
    }
}

This Code runs on https://play.kotlinlang.org. But in IDEA, they cannot understand it, showing 'Unresolved reference'.

I`ve searched but no answer found. How can I run this on IDEA project?

Temp
  • 109
  • 1
  • 11
  • 1
    You need to declare all dependencies. https://github.com/Kotlin/kotlinx.coroutines – tynn May 29 '19 at 10:05
  • The code works fine on Intellij IDEA 2019.1, kotlin 1.3.31 without any changes. – Nolequen May 29 '19 at 11:57
  • @Nolequen How did you setup these dependencies? I made 'Gradle Kotlin Build Script' and pasted them to file but nothing did work well. – Temp May 29 '19 at 12:11
  • you may refer to official documentation about how to setup kotlin project using gradle: https://kotlinlang.org/docs/reference/using-gradle.html – Nolequen May 29 '19 at 12:14
  • @Nolequen I need your help. I am newbie at this and I cannot find any right place to set a code. When I tried running kts, it shows some bulb icon. After clicked it, IDEA added some jar for running kotlin script at KotlinJavaRuntime.xml Then I thought if i add something correct, it will run. But of course failed. Should I use other project like Gradle - Kotlin/JVM or Java - Kotlin/JVM to setting well? I will try more. Please give me some hint that I can use – Temp May 29 '19 at 14:29
  • I gave up using kotlin - JVM | IDEA. I make another one using Gradle - Kotlin/JVM and there is default build.gradle for setting. Finally successed – Temp May 30 '19 at 02:34
  • @Temp I'm glad that everything worked out :) – Nolequen May 30 '19 at 06:49

1 Answers1

0

it would be a good idea to switch to a Gradle-based build, which will automatically be imported by IntelliJ IDEA.

you can set IntelliJ to automatically stay in sync with your Gradle files, or you can opt to "sync" IntelliJ to Gradle's structure on demand.

you have two syntax options with Gradle: Groovy and Kotlin. make sure if you are new to Gradle that you use a consistent syntax, otherwise it can be hard to follow the guides. obviously if you are working in Kotlin, it's a great idea to use Kotlin in your build files, too.

Sam Gammon
  • 1,457
  • 10
  • 16