kotlinpackagekotlinc

kotlinc: unresolved reference


I have two files:

Main.kt:

package A

fun gg1() = "hello"

Main2.kt:

package B
import A.gg1

fun gg2() = gg1()

Trying to compile the code:

iv@LAPTOP:~$ tree .
.
├── A
│   └── Main.kt
└── B
    └── Main2.kt

2 directories, 2 files
iv@LAPTOP:~$ kotlinc B/Main2.kt
B/Main2.kt:3:8: error: unresolved reference: A
import A.gg1
       ^
B/Main2.kt:5:13: error: unresolved reference: gg1
fun gg2() = gg1()
            ^
iv@LAPTOP:~$

Why do i get this error and how to fix it ?


Solution

  • You're only passing B/Main2.kt to kotlinc. You need to pass the other file too if you want the compiler to be aware of its existence.

    Imports don't work as file/path references: the import A.gg1 doesn't tell the compiler to look for A/Main.kt (how would it know the file name?). There is no technical relation between the package names and the paths of the files, just a convenient convention.

    In fact, imports are mostly syntax sugar to avoid using fully qualified names within the code (so the code itself looks a bit simpler), but they are not necessary per se, and you could just use declarations without imports if you wanted to (except in some specific cases).

    Maybe this related question could shed some light too: How does import find the file path in Kotlin?