Exit in Kotlin
Here’s an idiomatic Kotlin example demonstrating the concept of program exit:
This Kotlin program demonstrates how to exit a program immediately with a specific status code. Let’s break down the code and explain its components:
We import
exitProcess
from thekotlin.system
package, which allows us to exit the program with a specific status code.In the
main
function, we first add a shutdown hook usingRuntime.getRuntime().addShutdownHook()
. This is similar to usingdefer
in Go, but it’s important to note that shutdown hooks in Kotlin are not guaranteed to run when usingexitProcess()
.We then call
exitProcess(3)
, which immediately terminates the program with a status code of 3. This is equivalent toos.Exit(3)
in Go.
To run this Kotlin program:
- Save the code in a file named
ExitExample.kt
. - Compile and run the program using the Kotlin compiler:
The echo $?
command displays the exit status of the last executed command, which in this case is 3.
Note that the shutdown hook message is not printed because exitProcess()
terminates the program immediately without running shutdown hooks or finalizers.
In Kotlin, like in Java, the main
function doesn’t return an integer to indicate the exit status. Instead, we use exitProcess()
to exit with a non-zero status code.
This example demonstrates how to handle program exit in Kotlin, which is conceptually similar to the Go example but uses Kotlin-specific syntax and idioms.