In this article, we will see how to pass command line arguments in Kotiln and how to access them in a program.
Inside the IntelliJ Idea editor, select
Run -> Edit Configurations
Add the command line parameters in Program arguments as shown below and click apply. In this case, we have added a name “John”.
We can use array notation to access the arguments. In this case, lets access the name as args[0].
fun main(args: Array<String>) { print("Hello " + args[0]) }
Output :
Hello John
In Kotlin, we can also use String template syntax for the concatenation. We can use any parameters inside ${} for this.
So, the above program can be rewritten as :
fun main(args: Array<String>) { print("Hello ${args[0]}") }
Output :
Hello John
We could also add a size check on the args array using isEmpty() to check if any command line parameter was entered :
fun main(args: Array<String>) { if(args.isEmpty()){ print("Please add some command line arguments") return } print("Hello ${args[0]}") }
If multiple command line arguments are entered, we can access them in a loop like below :
fun main(args: Array<String>) { for(str in args) println("Hello ${str}") }
© 2018, https:. All rights reserved. On republishing this post, you must provide link to original post