Main.kts script unresolved reference has a problem with ktor example code

#!/usr/bin/env kotlin

@file:DependsOn("io.ktor:ktor-client-core:1.6.5")
@file:DependsOn("io.ktor:ktor-client-cio:1.6.5")

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO

val client = HttpClient(CIO)

The above Kotlin script has errors:
Unresolved reference: HttpClient
Unresolved reference: CIO

The io.ktor.client part are ok I think. The above in a Kotlin Gradle project with a main works fine.

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO

suspend fun main() {
    val client = HttpClient(CIO)
}

This is rather unfortunate, a new person such as me falls into the mess thinking oh I can script ktor. First issue is KMM I discovered and the meta class. However, I did find the jvm jars and ended with the below. It doesn’t work resulting in further errors, but I give up on it not worth it compared to just building an executable jar style as shown in the examples on ktor.io.

Kinda gives an idea on how much magic Gradle is doing. Hopefully someday it is a simple affair to script with ktor.

#!/usr/bin/env kotlin -classpath dependent/ktor-client-core-jvm-1.6.5.jar:dependent/ktor-client-cio-jvm-1.6.5.jar:dependent/ktor-http-jvm-1.6.5.jar:dependent/ktor-http-cio-jvm-1.6.5.jar:dependent/ktor-utils-jvm-1.6.5.jar:dependent/ktor-network-jvm-1.6.5.jar:dependent/ktor-network-tls-jvm-1.6.5.jar:dependent/ktor-io-jvm-1.6.5.jar:dependent/kotlinx-coroutines-core-jvm-1.5.2-native-mt.jar:

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.statement.HttpResponse
import io.ktor.client.request.get

val client = HttpClient()

GlobalScope.launch(Dispatchers.Main) {
    val response: HttpResponse = client.get("https://ktor.io/")
    println(response.status)
    client.close()
}

Ok this worked, but not fun to figure out. I put it here just in case someone else heads down the rabit hole I did. Such a naive thought I could script ktor, oops. The classpath hell is unfortunate, need a fat jar I guess.

#!/usr/bin/env kotlin -classpath dependent/ktor-client-core-jvm-1.6.5.jar:dependent/ktor-client-cio-jvm-1.6.5.jar:dependent/ktor-http-jvm-1.6.5.jar:dependent/ktor-http-cio-jvm-1.6.5.jar:dependent/ktor-utils-jvm-1.6.5.jar:dependent/ktor-network-jvm-1.6.5.jar:dependent/ktor-network-tls-jvm-1.6.5.jar:dependent/ktor-io-jvm-1.6.5.jar:dependent/kotlinx-coroutines-core-jvm-1.5.2-native-mt.jar:

import kotlinx.coroutines.runBlocking

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.statement.HttpResponse
import io.ktor.client.request.get

suspend fun scriptMain() {
    val client = HttpClient(CIO)
    val response: HttpResponse = client.get("https://ktor.io/")

    println(response.status)
    client.close()
}

runBlocking {
    scriptMain()
}