Search code examples
kotlinkotlin-script

How to include a jar file in kotlin script


I want to separate some generic code from my kotlin script file so that it can be reused.

I did this:

// MyLib.kt

package myLib
fun say_hello(name : String)
{
   println("hello $name")
}

I compiled this file to create a jar file:

kotlinc myLib.kt -include-runtime -d myLib.jar

Then I created a script file:

// myScript.kts

import myLib.*
say_hello("Arvind")

But i can not compile the script file as it neither recognizes myLib package nor say_hello() function.

What is the correct way to do this.

Question Update: I am using kscript to run my script. Typing a lot e.g.,

kotlin -cp myLib.jar myScript.kts

every time I have to run the script, thus defeats the motive of using kscript.

Is not there any way so that I need not give path of jar every time command line. Instead I want to use it in a kscript way, i.e.

./myScript

Solution

  • You need to include the myLib.jar in the classpath, for example:

    kotlin -cp myLib.jar myScript.kts
    

    Also, you do not need to compile myLib with -include-runtime, unless you want to create a self-contained and runnable jar (see example).

    Update:

    Rename myScript.kts to myScript.main.kts and change its content to:

    #!/usr/bin/env kotlin
    
    @file:DependsOn("myLib.jar")
    
    import myLib.*
    
    say_hello("Arvind")
    

    You now can call it (don't forget to set execute permissions):

    ./myScript.main.kts
    

    If instead of the myLib.jar file you want to include the myLib.kt script replace @file:DependsOn("myLib.jar") by @file:Import("myLib.kt").