I am attempting to accept input from the console in Kotlin but it is difficult because I am not too sure about the syntax.
I begin with the main
fun main(args: Array<String>) {
}
WHAT should I enter after this? I am aware that the println()
and readline()
are involved but I do not know how to structure them.
Objective: prompt user to enter a number, the number entered is multiplied by 6, program returns the result to the console display.
Use readLine() to take input from user, ATQ:
Here are A+B examples in Kotlin reading from stdin:
or
or
or
or
Beware that Scanner is somewhat slow. This may be important in some cases like competitive programming where program's execution on large inputs could be made up to two times faster just by replacing Scanner with plain readLine.
I hope someday a concise, crossplatform, performant, universal for both console and files input parsing support would be introduced in Kotlin stdlib. Like
readInt
,readLong
, etc global andReader
extension functions.Bonus
Sometimes you start with console input/output but then need to switch to files. It becomes too tedious to prepend every read or write call with file stream variable.
Here is a peace of Kotlin magic that allows to just wrap unchanged console code with a couple of lines to force it read and write to files also ensuring they are closed properly:
Wrapping lines can be quickly commented out when happens a need to switch back to console.
By default readLine takes input as string toInt can be used to convert it to integer