Determine Operating System in Kotlin
This article explores different ways to programmatically determine the current operating system from Kotlin.
We can access the System’s environment variables with the System.getProperty() function. The idea is to get the os.name system property to determine the operating system.
Following is a simple example demonstrating this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
enum class OS { WINDOWS, LINUX, MAC, SOLARIS } fun getOS(): OS? { val os = System.getProperty("os.name").toLowerCase() return when { os.contains("win") -> { OS.WINDOWS } os.contains("nix") || os.contains("nux") || os.contains("aix") -> { OS.LINUX } os.contains("mac") -> { OS.MAC } os.contains("sunos") -> { OS.SOLARIS } else -> null } } fun main() { when (getOS()) { OS.WINDOWS -> println("Windows Operating System") OS.LINUX -> println("Linux Operating System") OS.MAC -> println("Mac Operating System") OS.SOLARIS -> println("Solaris Operating System") else -> println("Unknown Operating System") } } |
Output (may vary):
Windows Operating System
That’s all about checking the operating system in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)