Kotlin in VS Code - Unresolved reference for user defined class in another file - kotlin

I'm trying to set up Kotlin for VS Code following the instructions in this article, which basically says to install the Kotlin and Code Runner extensions.
So far, so good, I am able to run the following code:
App.kt:
fun main() {
MyApp().printTest()
}
class MyApp {
fun printTest() {
println("Hello test")
}
}
However, when I try to extract the MyApp class to another file in the same folder, I can't import it:
App.kt:
import MyApp.MyApp // import MyApp doesn't work also
fun main() {
MyApp().printTest()
}
MyApp.kt:
class MyApp {
fun printTest() {
println("Hello test")
}
}
I've tried to import the Java Import Snippets extension, but it doesn't work, showing a unresolved reference for MyApp.
Am I missing some extension or VS Code configuration?
That's the command VS Code is running:
cd ".../testapp/src/" && kotlinc App.kt -include-runtime -d App.jar && java -jar App.jar
Should it reference MyApp.kt somehow?
Note: I'm on Debian.

You have no project's package name defined.
Put the files App.kt and MyApp.kt in the same folder level.
In App.kt, only use
import MyApp // or no import at all,
fun main() {
MyApp().printTest()
}
Read more about Java/Kotlin package

Related

How do you run a kotlin file that accesses another file in vs code

on vs code, i have a folder called master on my desktop with 2 kotlin files, main.kt and foo.kt.
main.kt's code
import master
fun main() {
println("hello")
foo()
}
foo.kt's code:
import master
fun foo(){
println("code from foo")
}
however, when i run kotlinc hello.kt -d hello.jar on the terminal of vs code, it says error: unresolved reference: foo
how can i resolve this? am i naming the packages wrong? I just want to run a very light kotlin package.

IntelliJ missing reference to slf4j in new Ktor project

I started a new Ktor project through their IntelliJ plugin and everything is compiling and running fine with Gradle. However in IntelliJ everything that references the slf4j logger is having a Unresolved reference: ... error.
My import and setting log leve looks like this (sorry my reputation is not high enough to post images):
The project is generated with the following dependencies
// gradle.properties
ktor_version=1.4.0
logback_version=1.2.1
// build.gradle.kts
dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version")
implementation("io.ktor:ktor-server-netty:$ktor_version")
implementation("ch.qos.logback:logback-classic:$logback_version")
implementation("io.ktor:ktor-server-core:$ktor_version")
implementation("io.ktor:ktor-auth:$ktor_version")
implementation("io.ktor:ktor-auth-jwt:$ktor_version")
implementation("io.ktor:ktor-jackson:$ktor_version")
testImplementation("io.ktor:ktor-server-tests:$ktor_version")
}
I have tried to add org.slf4j:slf4j-nop:1.7.30 to my dependencies without any luck.
So my questions is, has anyone seen this error before and know if there is a dependency or setting i could change? It is annoying to not have any code completion and errors scattered around the IDE even though it compiles and run fine.
The full application code generated with the Ktor plugin is below if needed:
package com.example
import io.ktor.application.*
import io.ktor.response.*
import io.ktor.request.*
import io.ktor.features.*
import org.slf4j.event.*
import io.ktor.routing.*
import io.ktor.http.*
import io.ktor.auth.*
import com.fasterxml.jackson.databind.*
import io.ktor.jackson.*
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
#Suppress("unused") // Referenced in application.conf
#kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
install(CallLogging) {
level = Level.INFO
filter { call -> call.request.path().startsWith("/") }
}
install(Authentication) {
}
install(ContentNegotiation) {
jackson {
enable(SerializationFeature.INDENT_OUTPUT)
}
}
routing {
get("/") {
call.respondText("HELLO WORLD!", contentType = ContentType.Text.Plain)
}
get("/json/jackson") {
call.respond(mapOf("hello" to "world"))
}
}
}
This was a caching issue with Gradle and IntelliJ, probably caused from other project dependencies. To IntelliJ the slf4j-api library was empty. Removing the global Gradle cache with rm -rf ~/.gradle/caches and re-download the dependencies solved the issue for me.

Runing coroutines in IntelliJ Kotlinx error

I'm trying to run a native Kotlin project using coroutines using IntelliJ IDEA Community 2020.
Here is how my build.gradle looks:
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.3.72'
}
repositories {
mavenCentral()
}
kotlin {
// For ARM, should be changed to iosArm32 or iosArm64
// For Linux, should be changed to e.g. linuxX64
// For MacOS, should be changed to e.g. macosX64
// For Windows, should be changed to e.g. mingwX64
mingwX64("mingw") {
binaries {
executable {
// Change to specify fully qualified name of your application's entry point:
entryPoint = 'sample.main'
// Specify command-line arguments, if necessary:
runTask?.args('')
}
}
}
sourceSets {
// Note: To enable common source sets please comment out 'kotlin.import.noCommonSourceSets' property
// in gradle.properties file and re-import your project in IDE.
mingwMain {
}
mingwTest {
}
}
}
// Use the following Gradle tasks to run your application:
// :runReleaseExecutableMingw - without debug symbols
// :runDebugExecutableMingw - with debug symbols
And here is a simple KT file:
package sample
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
val deferred = async(Dispatchers.Unconfined, CoroutineStart.LAZY) {
println("Running Async Unconfined: on thread ${Thread.currentThread().name} has run.")
42
}
val result = deferred.await()
println("Async Unconfined Result is ${result}")
}
I installed the maven plugin under Project Structure | Module and screenshot attached.
Nevertheless, I'm getting "Unresolved References..." error. Attached screenshot...
Request if someone can help me to resolve this please?
Thanks
In your Project Structure > Modules > Dependencies tab, you selected Runtime as the scope, which makes the dependency only available at runtime (usually used for transitive dependencies). Try selecting Compile here.

kotlin program error: no main manifest attribute in jar file

I wrote a simple kotlin helloworld program
hello.kt
fun main(args: Array<String>) {
println("Hello, World!")
}
Then I compiled it with kotlinc
$kotlinc hello.kt -include-runtime -d hello.jar
there was no errors and hello.jar was generated.
when I ran it
$java -jar hello.jar
it said there is no main manifest attribute in hello.jar
$no main manifest attribute, in hello.jar
I couldn't figure out this problem.
My kotlin version is 1.3.40, JDK version is 1.8.0
I came accross this answer while having the same issue with Kotlin and gradle. I wanted to package to get the jar to work but kept on pilling errors.
With a file like com.example.helloworld.kt containing your code:
fun main(args: Array<String>) {
println("Hello, World!")
}
So here is what the file build.gradle.kts would look like to get you started with gradle.
import org.gradle.kotlin.dsl.*
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
application
kotlin("jvm") version "1.3.50"
}
// Notice the "Kt" in the end, meaning the main is not in the class
application.mainClassName = "com.example.MainKt"
dependencies {
compile(kotlin("stdlib-jdk8"))
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}
tasks.withType<Jar> {
// Otherwise you'll get a "No main manifest attribute" error
manifest {
attributes["Main-Class"] = "com.example.MainKt"
}
// To avoid the duplicate handling strategy error
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
// To add all of the dependencies otherwise a "NoClassDefFoundError" error
from(sourceSets.main.get().output)
dependsOn(configurations.runtimeClasspath)
from({
configurations.runtimeClasspath.get().filter { it.name.endsWith("jar") }.map { zipTree(it) }
})
}
So once you gradle clean build you can either do:
gradle run
> Hello, World!
Assuming your projector using the jar in build/libs/hello.jar assuming that in your settings.gradle.kts you have set rootProject.name = "hello"
Then you can run:
java -jar hello.jar
> Hello, World!
Try to upgrade to version 1.3.41 and using JDK 1.11+.

Kotlin compiler does not find import kotlin.test

I'm trying to compile the following via command-line:
import kotlin.test.assertTrue
fun main(args: Array<String>) {
assertTrue(false)
}
However, the compiler fails with:
$ kotlinc -d MyCode.jar MyCode.kt
MyCode.kt:1:15: error: unresolved reference: test
import kotlin.test.assertTrue
^
What am I missing?
Are org.jetbrains.kotlin:kotlin-test and org.jetbrains.kotlin:kotlin-test-junit specified in dependencies? kotlin.test is not a base module