4

I am experimenting with the use of Kotlin as a scripting language. According to their docs, you should be able to run top-level code in a Kotlin script.

A simple "Hello, World" program I wrote using their official example is not outputting any text. It compiles/interprets, terminates successfully, but it appears that the println() statement does nothing

fun main(args: Array<String>) {
    println("Hello, World!")
}

Does anyone know where I can find a table / summary of what is actually supported when using Kotlin as a scripting language? What am I missing in making it do a simple print statement.

I am running using a Kotlin SDK installed via sdkman on Ubuntu. Running from the vanilla terminal provided with Ubuntu. The expected output would be a line where "Hello, World!" is shown, but there is no output at all.

bbuck
  • 129
  • 10

1 Answers1

9

A function in it self does not get executed. Its a declaration like a variable. In a script it must be invoked.

fun main() { // removed unused args
    println("Hello, World!")
}

// Add this
main()
  • 1
    Thank you in retrospect this should have been obvious, but I was taking the code snippet from Kotlin’s official and expected it “just work”. D’oh – bbuck Jan 27 '20 at 17:25
  • 1
    This seems weird. My local `kotlin` runs everything on the top-level while the Google Code Jam judge for example will run my main function by default. Must be some configurable compiler option or something. – xjcl Jun 30 '21 at 21:50
  • 1
    It seems like `kotlin a.kts` requires an explicit call to `main`, while `kotlinc a.kt && kotlin AKt` already jumps into `main`. – xjcl Mar 10 '22 at 18:18