简体   繁体   中英

unresolved reference error for callable in another Kotlin file

I'm new in Kotlin (came from Python) and I'm trying to recreate a tic-tac-toe game.

I'm trying to use a class from another file but i just get this error when i compile the main file:

main.kt:2:21: error: unresolved reference: TicTacToeBoard
    var tabuleiro = TicTacToeBoard()
                    ^

In the directory, called "tictactoe", i have the "main.kt" and "board.kt" files:

The "main.kt" file:

fun main(args: Array<String>) {
    var tabuleiro = TicTacToeBoard()
}

The "board.kt" file:

class TicTacToeBoard

有两个文件和错误的目录

The same happens with functions from another file.

I've seen a lot of articles and videos where this same syntax work. What am i missing? why is this not working? and how can i use classes from another file on the main file?

EDIT 1: (more information)

I'm using VSCODE and running the file with the code runner extension on default settings.

kotlin information: Kotlin version 1.6.21-release-334 (JRE 18.0.1.1+2-6)

Your code is fine and has no problems. Kotlin auto import functions and classes from files on the same directory (not like python, where you need to manually import stuff).

The problem is how are you running the code. You are compiling main.kt without compiling all the files it needs. In this case, you need to compile the board.kt first, then compile the main.kt, and then run the jar file. Ex:

$ kotlinc board.kt, main.kt -include-runtime -d main.jar
$ java -jar main.jar

.

In case your project grows and it becomes unfeasible to write the name of all the files in the correct order, you can (and should) compile all the files at the same time.

Ex. using the "*" wildcard character:

$ kotlinc *.kt -include-runtime -d main.jar

Ex. in case the "*" does not work, you can use just a dot ".":

$ kotlinc . -include-runtime -d main.jar

Then you run the java file as usual.

.

Since you are using the CodeRunner to run the code, you should edit its configuration file to compile all files at once.

STEP 1: Go to the extension page on the extension market and click the gear, then "extension configuration" 扩展页面

STEP 2: Search for "executor map", then, "edit json" 扩展配置

STEP 3: On the json file, look for "kotlin" and edit the "$filename" to the dot or asterisk (whatever work for you) 编辑默认代码运行器

STEP 4: Save the file and you're good to go

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM