Home > Software design >  How to import a file from another directory in Kotlin?
How to import a file from another directory in Kotlin?

Time:12-26

I have a gradle kotlin project, and I'm generating a kotlin file from a Rust project, so it ends up in a totally different place with no gradle project structure, etc.

How do I import this file into my gradle project?

It has its own package but it's a completely standalone file. This is my gradle file:

rootProject.name = "my_project"
include("app")

It's a desktop project, NOT android.

My build.gradle.kts:

plugins {
    // Apply the org.jetbrains.kotlin.jvm Plugin to add support for Kotlin.
    id("org.jetbrains.kotlin.jvm") version "1.5.31"

    // Apply the application plugin to add support for building a CLI application in Java.
    application
}

repositories {
    // Use Maven Central for resolving dependencies.
    mavenCentral()
}

dependencies {
    // Align versions of all Kotlin components
    implementation(platform("org.jetbrains.kotlin:kotlin-bom"))

    // Use the Kotlin JDK 8 standard library.
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")

    // This dependency is used by the application.
    implementation("com.google.guava:guava:30.1.1-jre")

    // Use the Kotlin test library.
    testImplementation("org.jetbrains.kotlin:kotlin-test")

    // Use the Kotlin JUnit integration.
    testImplementation("org.jetbrains.kotlin:kotlin-test-junit")
}

application {
    // Define the main class for the application.
    mainClass.set("my_project.ffi.AppKt")
}

CodePudding user response:

Adding the following code to your build.gradle.kts should do the trick (tested with Gradle 7.3.2):

// TODO: replace this dummy task with the task from your Rust project which
//  generates the Kotlin source directory. Make sure that the generated
//  directory (with the Kotlin file(s)) is the task output directory.
val rustTask by tasks.registering(Copy::class) {
    // To test this, I had simply put a Kotlin file into this "somewhere"
    // directory.
    from("somewhere")
    into(temporaryDir)
}

sourceSets {
    main {
        java {
            srcDir(rustTask)
        }
    }
}

tasks {
    compileKotlin {
        dependsOn(rustTask)
    }
}

So, we’re simply adding the generated sources as an additional source directory to the default SourceSet which is consumed by the compileKotlin task. In addition, we make sure that the sources are generated before compileKotlin runs.

  • Related