Kotlinc example with separate files

I have created a function in a file and compiled it per the kotlinc example without the runtime. Now I want to use that function in a “main file” kotlin program, but I don’t know to do it. It there a kotlinc example that uses code from two files?

Consider as this is a main file
#Main.kt

fun main(args: Array) {
helloBoss() /helloBoss is a method declare in second file name as HelloToBoss.kt/
}

and other one is second kotlin file with a function hello to BOSS

#HelloToBoss.kt

fun helloBoss() {
println("hello boss ")
}

Thanks for the response. Main.kt needs something else in order to get it to compile. I don’t know what that is.

You need to compile HelloToBoss.kt first: kotlinc HelloToBoss.kt, then compile Main.kt: kotlinc -cp . Main.kt. Assume the 2 files are inside same directory. Or you can just compile the 2 files at the same time: kotlinc *.kt.

I needed to add a package and import statement:

Main.kt

import liby.helloBoss // or “import liby.*”

fun main(args: Array<String>) {
    /*helloBoss is a method declare in second file name as HelloToBoss.kt*/
     helloBoss() 
}

and other one is second kotlin file with a function hello to BOSS
HelloToBoss.kt

package liby;

fun helloBoss() {
   println("hello boss ")
}

Thanks. I can compile with either of those formats, but I do get an error on trying to run it:

java -cp . MainKt
Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics
	at MainKt.main(Main.kt)
Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.Intrinsics
	at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
	at java.lang

If I link in the Kotlin runtime as they show on their kotlinc page:

kotlinc -cp . -include-runtime Main.kt

I get the same error as above. But I notice the strange behavior that I can only do the kotlinc command with the -include-runtime right after a kotlinc *.kt command. If it is run again it gives an error:

 kotlinc -cp . -include-runtime Main.kt
Main.kt:5:5: error: unresolved reference: helloBoss
    helloBoss() /*helloBoss is a method declare in second file name as HelloToBoss.kt*/
    ^

my compile output is:

MainKt.class 
                   /liby
                          HelloToBoss.class

For your case, you can just compile the 2 files at the same time: kotlinc -include-runtime -d hello.jar Main.kt liby/HelloToBoss.kt. Then you can use java -jar hello.jar to execute the application.

Thanks, that worked! I read somewhere that Kotlin doesn’t require packages to line up with directories, but it seems to work the way Java does (from what I remember of Java).

@kotlinsky1 From another angle: are you using an IDE?

I have IntelliJ IDEA installed and have used it, but prefer to only use an Editor at this point while I am learning.