Search code examples
kotlinserverktor

Ktor: "could not find or load main class"


I know similiar questions have already been asked but none of the solutions worked for me, so I gotta ask myself. I have a Kotlin Multiplatform project in which I'm trying to set up a server that does some web scraping for me. The problem is, when starting the server the program cant find main class "ApplicationKt" apparentely.

What I already tried: invalidate caches, restart laptop and android studio, run command with --warning-mode all (dont get any more information).

The error code:

> Task :server:run FAILED
Fehler: Hauptklasse de.takedown.ApplicationKt konnte nicht gefunden oder geladen werden
Ursache: java.lang.ClassNotFoundException: de.takedown.ApplicationKt

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':server:run'.
> Process 'command 'D:\Program Files\Android\Android Studio\jbr\bin\java.exe' finished with non-zero exit value 1

My gradle file (server module):

val ktor_version = "2.3.8"
val htmlUnitVersion = "3.7.0"

plugins {
    alias(libs.plugins.ktor)
    application
}

application {
    // Entry Point
    mainClass.set("de.takedown.ApplicationKt")
    applicationDefaultJvmArgs = listOf("-Dio.ktor.development=${extra["development"] ?: "false"}")
}

dependencies {
    implementation("io.ktor:ktor-server-core:$ktor_version")
    implementation("io.ktor:ktor-server-netty:$ktor_version")

    // HTMLUNIT
    implementation("org.htmlunit:htmlunit:3.10.0")
}

Application.kt file code:

fun main() {
    embeddedServer(Netty, port = 8080) {
        routing {
            get("/") {
                // example code
            }
        }
    }.start(wait = true)
}

I'm really lost at what I'm doing wrong, would really appreciate any help.


Solution

  • You need to apply the Kotlin JVM plugin to compile the Kotlin code.

    plugins {
        kotlin("jvm") version "1.9.20" // version must be omitted if already on classpath
        alias(libs.plugins.ktor)
    }
    

    (It is not necessary to separately apply the Application plugin as this is applied by the Ktor plugin.)

    Other things to also ensure that aren't clear from your question:

    • Add the imports for all the Ktor classes to Application.kt
    • Make sure Application.kt is in the src/main/kotlin/de/takedown folder