skip to Main Content

directory structure

MyFun.kt

fun sayHello() {
    println("Hello")
}

Main.kt

import MyFun.kt

fun main() {
    sayHello()
}

I tried typing import MyFun and import MyFun.*
Result is alway the same:

[Running] cd "c:Usersdov4k1nDocumentsGitHubOtherTestImporting" && kotlinc tempCodeRunnerFile.kt -include-runtime -d tempCodeRunnerFile.jar && java -jar tempCodeRunnerFile.jar
tempCodeRunnerFile.kt:1:8: error: unresolved reference: MyFun
import MyFun.kt
       ^
tempCodeRunnerFile.kt:4:5: error: unresolved reference: sayHello
    sayHello()
    ^

[Done] exited with code=1 in 6.588 seconds

tried in command line as well:

C:Usersdov4k1nDocumentsGitHubOtherTestImporting>kotlinc Main.kt MyFun.kt -include-runtime -d Main.jar
Main.kt:1:8: error: unresolved reference: MyFun
import MyFun.kt
       ^

i expect to use functions from MyFun.kt in Main.kt to organize my project in different files. In intellij IDEA error message is the same. don’t know what to do 🙁

i use: windows 11 64bit, kotlin 1.9.0, jdk 20, jre 8u381 win64, code runner in vscode, kotlin language by mathiasfrohlich

2

Answers


  1. Chosen as BEST ANSWER

    Thank you, @Tenfour04 ! I apologize

    1. I removed "import MyFun.kt" from the top of the Main.kt and then typed kotlinc Main.kt MyFun.kt -include-runtime -d Main.jar in the command line. No compilation error this time, and then typed "java -jar Main.jar" and it returned "Hello" as i wanted

    2. Then created folder "com" in the folder "TestImporting", moved MyFun.kt there, added "package com.sample" at the top of MyFun.kt, added "import com.sample.sayHello" at the top of Main.kt. Then typed kotlinc Main.kt com/MyFun.kt -include-runtime -d Main.jar, no compilation error. Then typed java -jar Main.kt and it returned "Hello" as i wanted


  2. In Kotlin, you don’t import files. You import classes or top-level functions. And if the thing you’re wanting to import is in the same package, you don’t need to import it at all.

    If these are the entire contents of each of your files, you haven’t defined any package for either of the files’ contents, so they’re both in the same package, the default nameless package, so there’s no need to import the function from one file in the other file.

    If you had defined a package for the MyFun.kt file like this:

    package com.sample
    
    fun sayHello() {
        println("Hello")
    }
    

    Then you would import this function in the other file like this:

    import com.sample.sayHello
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search