Trying to run Kotlin script in IntelliJ IDEA - intellij-idea

I am learning Kotlin by doing Kotlin Koans int IntelliJ EduKotlin plugin (https://plugins.jetbrains.com/plugin/8186). While doing tasks and running them im this plugin is working, I am not able to create new Kotlin script and run it without this plugin.
Sample code in a file named Hello.kt:
fun hello() : String {
return "ok"
}
Then I create new run configuration derived from 'Kotlin script', set 'Working directory' to ProjectName/src folder (or ProjectName folder, same result) and IDE shows me a 'Could not find script file: Hello.kt' warning as in the screen below:
And indeed, while trying to run script I got following stacktrace:
"C:\Program Files\Java\jdk1.8.0_74\bin\java" -Dfile.encoding=windows-1250 -classpath C:\Users\myUser\.IdeaIC2016\config\plugins\Kotlin\kotlinc\lib\kotlin-compiler.jar;C:\Users\myUser\.IdeaIC2016\config\plugins\Kotlin\kotlinc\lib\kotlin-reflect.jar;C:\Users\myUser\.IdeaIC2016\config\plugins\Kotlin\kotlinc\lib\kotlin-runtime.jar org.jetbrains.kotlin.cli.jvm.K2JVMCompiler -script Hello.kt
exception: java.lang.RuntimeException: Failed to evaluate script: kotlin.KotlinNullPointerException
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileScript(KotlinToJVMBytecodeCompiler.kt:263)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileAndExecuteScript(KotlinToJVMBytecodeCompiler.kt:212)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:181)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:49)
at org.jetbrains.kotlin.cli.common.CLICompiler.exec(CLICompiler.java:181)
at org.jetbrains.kotlin.cli.common.CLICompiler.exec(CLICompiler.java:138)
at org.jetbrains.kotlin.cli.common.CLICompiler.exec(CLICompiler.java:57)
at org.jetbrains.kotlin.cli.common.CLICompiler.doMainNoExit(CLICompiler.java:248)
at org.jetbrains.kotlin.cli.common.CLICompiler.doMain(CLICompiler.java:238)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler$Companion.main(K2JVMCompiler.kt:248)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.main(K2JVMCompiler.kt)
Caused by: kotlin.KotlinNullPointerException
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileScript(KotlinToJVMBytecodeCompiler.kt:475)
... 10 more
Process finished with exit code 2
What more, the hello method is marked as never used. However, when I change file extension from .kt to .ktscript, then this method is marked as used, and the output from running code is following:
"C:\Program Files\Java\jdk1.8.0_74\bin\java" -Dfile.encoding=windows-1250 -classpath C:\Users\myUser\.IdeaIC2016\config\plugins\Kotlin\kotlinc\lib\kotlin-compiler.jar;C:\Users\myUser\.IdeaIC2016\config\plugins\Kotlin\kotlinc\lib\kotlin-reflect.jar;C:\Users\myUser\.IdeaIC2016\config\plugins\Kotlin\kotlinc\lib\kotlin-runtime.jar org.jetbrains.kotlin.cli.jvm.K2JVMCompiler -script Hello.kt
error: source file or directory not found: Hello.kt
Process finished with exit code 1
So my question is: what am I missing when trying to create and run Kotlin code in a standalone Kotlin script in IntelliJ?

A standalone Kotlin script file needs to have a .kts extension. If you rename your file, you also need to make sure that your run configuration is updated to refer to the new name of the file.
Also, if you create any file (a regular Kotlin file or a .kts file) which only contains a function, running the script will not produce any output, because the function will not be called. To see some output, you need to call the function in your script:
fun hello(): String {
return "ok"
}
println(hello())
The stacktrace that you saw is a bug in Kotlin.

Related

Error: Could not find or load main class MainKt

In Multiplatform project, I want to use main function inside jvmMain to test the library I’m working on, but when I’m trying to run this it returns an error Error: Could not find or load main class MainKt for following function in Main.kt
fun main() {
println("Hello World!")
}
I've got Main.kt file in a root directory of my module, but putting it under some package is also throwing this error.
I'm using Java 8 JDK:
Are there any additional steps I should make to be able to use main function?
EDIT:
I did additional checks and I found out that when in the project I have android target then in the jvm main function I’m getting this error above. When I’m creating a new project with exactly the same configuration, but without android target it’s working properly, main function compiles and it is printing a message.
Any guess what is causing this problem?

How to run main function Kotlin file on command-line with string array arguments

i'm trying to run one of .kt files that i have for my side project and I suddenly wanted run my *.kt file that has
fun main(args: Array<String>) {
...
}
on command-line tool. I did install kotlin compiler, set up the path. All I have to do is to figure out how to pass args parameter through command line and cannot find a way to do that.
I've looked through kotlin compiler options and how to run kotlin file on command-line and it did not help at all.
Thanks in advance.
Just type them after the command:
java -jar myjar.jar arg_one arg_two
//OR (After compiling to jars you can specify the main class to run)
kotlin -classpath myjar.jar MyKt 'arg_one' 'arg_two'
//OR
kotlin MyKt 'arg_one' 'arg_two'
Then:
val argOne = args[0] // "arg_one"
First you have to compile your file to a JAR:
kotlinc filename.kt -include-runtime -d output.jar
Then you can run that JAR with java:
java -jar output.jar argument0 argument1

Can not run Clojure project with Cursive using Leiningen

I am unable to run a simple test project using the intellij plugin cursive. I am able to open a REPL without any problems and can even call functions defined in the core.clj file.
Running the project directly however yields this error message:
Error running 'new-project.core': failed to access class com.intellij.execution.impl.ProcessStreamsSynchronizer from class com.intellij.execution.impl.ConsoleViewRunningState (com.intellij.execution.impl.ProcessStreamsSynchronizer is in unnamed module of loader com.intellij.util.lang.UrlClassLoader #402f32ff; com.intellij.execution.impl.ConsoleViewRunningState is in unnamed module of loader com.intellij.ide.plugins.cl.PluginClassLoader #c9a79eb)
Intellij run configuration here. Changing How to run it and What to run does nothing.
Starting the project via the Leiningen tab yields the same error message.
There is an issue open about it.
https://github.com/cursive-ide/cursive/issues/2350
Also I tried to do lein run Let me know if this work for you.

How run flutter 'packages pub run build_runner build' with debug mode in intellij idea?

I want to put break point on my generator code, but I don't know how to run the command on the debug mode.
I wrote generator using source_gen and build_runner
class MyGenerator extends GeneratorForAnnotation<Todo> {
#override
FutureOr<String> generateForAnnotatedElement(
Element element, ConstantReader annotation, BuildStep buildStep) {
return "// Hey! Annotation found!";
}
}
run commad flutter packages pub run build_runner build*
copy build.dart to root folder of project
add new run configuration
run debug, now you can debug your code generator!
* the packages is optional, you can just run flutter pub run build_runner build
Ivan's answer worked for me, but every time I changed a file that was using an annotation - the build process outputted:
[SEVERE] Terminating builds due to build script update
[INFO] Terminating. No further builds will be scheduled
and then renamed the build script itself from build.dart to build.dart.cached, and then exit with code 75.
After digging through the build_runner code, I discovered that this behavior can be mitigated by using the following Program Arguments:
serve --skip-build-script-check
(i.e. instead of just serve as Ivan suggested).
There may be some negative consequences; in the build_runner source code, in options.dart, I saw this:
// For testing only, skips the build script updates check.
bool skipBuildScriptCheck;

Kotlin Script (.kts) - How to divide it into multiple files?

I have a Generator.kts file. When I execute it using:
kotlinc -script Generator.kts
everything works as expected.
However, now my script has grown and I need to separate that class into multiple files.
I did that but when I try to execute it again I get the following errors:
Generator.kts:8:23: error: unresolved reference: CSVReader
val csvData = CSVReader().readCSV()
^
Generator.kts:10:23: error: unresolved reference: Folders
val folders = Folders()
^
Generator.kts:14:9: error: unresolved reference: KeyStore
KeyStore().generateKeyStoreFile(
Basically it fails to find all of the classes I created (CSVReader.kt, Folders.kt and KeyStore.kt). All those classes are in the same folder (including Generator.kts).
How can I run a Kotlin script that uses multiple files?
You could either compile all your sub-scripts into an artifact and add it to the classpath
Or you could use a third party tool like kscript to include them on the fly into your master script.
#!/usr/bin/env kscript
#file:Include("utils.kt")
val robustMean = listOf(1.3, 42.3, 7.).median()
println(robustMean)
For details and examples see https://github.com/holgerbrandl/kscript#ease-prototyping-with-include
Disclaimer: I'm a contributor of kscript.