Writing scripts with Kotlin

As previously stated, Kotlin can be used to write scripts. Scripts are programs that are written for specific runtime environments for the common purpose of automating the execution of tasks. In Kotlin, scripts have the .kts file extension appended to the file name.

Writing a Kotlin script is similar to writing a Kotlin program. In fact, a script written in Kotlin is exactly like a regular Kotlin program! The only significant difference between a Kotlin script and regular Kotlin program is the absence of a main function.

Create a file in a directory of your choosing and name it NumberSum.kts. Open the file and input the following program:

val x: Int = 1
val y: Int = 2
val z: Int = x + y
println(z)

As you've most likely guessed, the preceding script will print the sum of 1 and 2 to the standard system output. Save the changes to the file and run the script:

kotlinc -script NumberSum.kts
A significant thing to take note of is that a Kotlin script does not need to be compiled.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.120.136