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

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

Related

How to pass javac options such as --add-exports to the Kotlin compiler?

I'm unable to set javac arguments when compiling a Kotlin file. The kotlinc -Xjavac-arguments option looks like the expected way to achieve this, but using Kotlin 1.8.0 and Java 17 this doesn't work.
For example, considering a simple .kt file with a single import from a non exported package:
import com.sun.tools.javac.util.Context
Invoking kotlinc with:
kotlinc -Xadd-modules=jdk.compiler -Xjavac-arguments=--add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED test.kt
gives:
test.kt:1:33: error: symbol is declared in module 'jdk.compiler' which does not export package 'com.sun.tools.javac.util'
import com.sun.tools.javac.util.Context
^
What am I missing?

How to have log4j.properties read env variables

This should just be a quick question. I am wondering if this syntax would be correct.
Inside log4j.properties
log4j.rootLogger=${ROOT_LOGGER:INFO}, console
So what I'm trying to achieve is to have a ROOT_LOGGER env variable and if it's not present, fallback to INFO. I know this works in .yaml files, so just wondering if the same applies here.
Long time but Im going to put my found solution here.
we can add vars on properties like:
${sys:some.property:-default_value}
${env:ENV_NAME:-default_value}
build.gragle dependencies
dependencies {
implementation "org.apache.logging.log4j:log4j-api:2.14.1"
implementation "org.apache.logging.log4j:log4j-core:2.14.1"
}
log4j2.properties
appender.consoledev.type=Console
appender.consoledev.name=CONSOLEDEV
appender.consoledev.layout.type=PatternLayout
appender.consoledev.layout.pattern=%d{HH:mm:ss.sss} %5p %20logger{36} : %msg%n
loggers=logapp
logger.logapp.name=${sys:logging.package:-com.test}
logger.logapp.level=${sys:logging.level:-DEBUG}
logger.logapp.additivity=false
logger.logapp.appenderRef.consoledev.ref=CONSOLEDEV
running jar with args
java -jar -Dlogging.level=INFO -Dlogging.package=com.test.MainClass test.jar
java -jar -Dlogging.level=INFO -Dlogging.package=com.test test.jar
java -jar -Dlogging.level=DEBUG -Dlogging.package=root test.jar

How to fix this bazel project for kotlin?

I want to be able to use bazel to organize a simple kotlin project.
I am using the templates as listed in rules_kotlin (https://github.com/bazelbuild/rules_kotlin)
This is my BUILD file
load("#io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kt_jvm_library")
kt_jvm_library(
name = "redis-tools",
srcs = glob(["*.kt"]),
deps = [],
)
This is my WORKSPACE file
load("#bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
rules_kotlin_version = "legacy-1.3.0"
rules_kotlin_sha = "4fd769fb0db5d3c6240df8a9500515775101964eebdf85a3f9f0511130885fde"
http_archive(
name = "io_bazel_rules_kotlin",
urls = ["https://github.com/bazelbuild/rules_kotlin/archive/%s.zip" % rules_kotlin_version],
type = "zip",
strip_prefix = "rules_kotlin-%s" % rules_kotlin_version,
sha256 = rules_kotlin_sha,
)
load("#io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kotlin_repositories", "kt_register_toolchains")
kotlin_repositories() # if you want the default. Otherwise see custom kotlinc distribution below
kt_register_toolchains() # to use the default toolchain, otherwise see toolchains below
My kotlin file main.kt:
import java.util.Scanner
fun main(args: Array<String>) {
// Creates a reader instance which takes
// input from standard input - keyboard
val reader = Scanner(System.`in`)
print("Enter a number: ")
// nextInt() reads the next integer from the keyboard
var integer:Int = reader.nextInt()
// println() prints the following line to the output screen
println("You entered: $integer")
}
I use a very simple file to test my setup.
Without bazel, I can do these to build: kotlinc main.kt -include-runtime -d test.jar
then run it with java -jar test.jar
When I use bazel build ., bazel creates a few folders. I tried to run java -jar bazel-out/darwin-fastbuild/bin/redis-tools.jar but it failed.
$ java -jar bazel-out/darwin-fastbuild/bin/redis-tools.jar
no main manifest attribute, in bazel-out/darwin-fastbuild/bin/redis-tools.jar
Did I miss a target? How can I run the main.tk from the bazel output?
The jar you are trying to run is missing a manifest file which declares its main class.
For executing a binary, Bazel uses a shell script wrapper which includes the required jvm flags and its run-time dependencies.
Notice that you are using kt_jvm_library. This rule builds a shared dependency without the wrapper. To include a wrapper you should use the kt_jvm_binary rule. Then you can specify the main class by setting the main_class attribute.
Notice that you can use the bazel run :redis-tools to run the jar (use -s to see which script Bazel excuted)
You can also use bazel build :redis-tools_deploy.jar to build a "fat-jar" which will include the manifest.

ktor running fat jar throws java.lang.UnsupportedOperationException::Packages and file facades are not yet supported in Kotlin reflection

Below is the basic ktor file which is running properly from IDE but I created a fat jar file with "mvn install" and running it throws below exception:
Exception in thread "main" java.lang.UnsupportedOperationException: Packages and file facades are not yet supported in Kotlin reflection. Meanwhile please use Java reflection to inspect this class: class com.tech.ApplicationKt
fun main(args: Array<String>){
embeddedServer(Netty, 8080){
routing{
get("/demo"){
call.respondText("Hello demo")
}
}
}.start(wait = true)
}
I tried executing jar on Java 11 and 8 but I am getting same exception.
I just tried this out by following the official guide on ktor.io for setup with maven.
Afterwards I followed https://ktor.io/servers/deploy/packing/fatjar.html#fat-jar-maven for the jar compilation.
I encountered 2 issues:
I first tried the install:install task from the IntelliJ Maven side bar, but actually you have to use the lifecycle methods install or just package.
I had to adjust the mainClass attribute of the maven assembly plugin to match that of my own, e.g path.to.your.package.ServerKt or whatever your file is called.
Once I fixed those two everything worked fine.
If you still have issues, please show us you build file.

Trying to run Kotlin script in 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.