Kotlin Tutoial
Basics
Control Flow
Array & String
Functions
Collections
OOPs Concept
Exception Handling
Null Safety
Regex & Ranges
Java Interoperability
Miscellaneous
Android
Kotlin, like Java, offers several ways to interact with the standard input (usually the keyboard) and standard output (usually the console). This tutorial will introduce you to the basics of standard input and output operations in Kotlin.
The most common way to print to standard output is using the print()
and println()
functions.
print(): This prints text to the console.
print("Hello, World!")
println(): This prints text to the console and then moves to a new line.
println("Hello, World!") println("Welcome to Kotlin!")
You can use string templates to include variable values directly within your output string:
val name = "Alice" println("Hello, $name!") // Outputs: Hello, Alice!
For more complex expressions, you can use ${}
:
val a = 5 val b = 10 println("Sum of $a and $b is: ${a + b}") // Outputs: Sum of 5 and 10 is: 15
To read from the standard input, you can use the readLine()
function, which reads a line of input from the console:
print("Enter your name: ") val name = readLine() println("Hello, $name!")
However, readLine()
returns a nullable string (String?
). If you're sure that the input won't be null (e.g., if you're not reading from a file), you can use the !!
operator. But use it with caution:
val input = readLine()!!
Often, you need to read specific data types from the input. Since readLine()
returns a string, you'll need to convert it. Here's how you can read different types:
Integers:
val number = readLine()!!.toInt()
Doubles:
val realNumber = readLine()!!.toDouble()
Lists:
If you want to read a list of integers separated by spaces:
val numbers = readLine()!!.split(" ").map { it.toInt() }
When dealing with user input, it's always a good idea to handle potential errors. For example, if you expect an integer but the user enters a string, your program will crash. Use a try-catch
block to handle such scenarios:
print("Enter a number: ") try { val number = readLine()!!.toInt() println("You entered: $number") } catch (e: NumberFormatException) { println("That's not a valid number!") }
Using standard input and output in Kotlin is straightforward and similar to many other languages. Leveraging Kotlin's string templates and extension functions can help you process and display data in a concise and readable manner. Always be cautious when dealing with external input, and handle potential errors gracefully.
Reading from standard input in Kotlin:
readLine()
function to read a line of text from the standard input.val input = readLine()
Using readLine()
for user input in Kotlin:
readLine()
and display the result.print("Enter your name: ") val name = readLine() println("Hello, $name!")
Parsing input values from the console in Kotlin:
print("Enter your age: ") val age = readLine()?.toIntOrNull() ?: 0
Handling standard output in Kotlin:
println()
to output text to the standard output.println("Hello, Kotlin!")
Printing to the console with println()
in Kotlin:
println()
.val variable = "World" println("Hello, $variable!")
Formatting output in Kotlin:
val pi = 3.14159 println("The value of pi is %.2f".format(pi))
Reading and writing files with Kotlin standard I/O:
FileReader
and FileWriter
for file I/O operations.val file = File("example.txt") val content = file.readText()
Scanner
class and standard input in Kotlin:
Scanner
class for more complex input parsing.val scanner = Scanner(System.`in`) val number = scanner.nextInt()
BufferedReader
and InputStreamReader
for input in Kotlin:
BufferedReader
.val reader = BufferedReader(InputStreamReader(System.`in`)) val line = reader.readLine()
PrintWriter
and BufferedWriter
for output in Kotlin:
PrintWriter
and BufferedWriter
.val writer = PrintWriter(BufferedWriter(FileWriter("output.txt"))) writer.println("Hello, file!") writer.close()
Redirecting standard input/output in Kotlin:
System.setIn(FileInputStream("input.txt")) System.setOut(PrintStream("output.txt"))
Console input/output in Kotlin console applications:
console.readLine("Enter your password: ") console.writer().println("Password accepted.")
Error handling for standard input/output operations in Kotlin:
try { val input = readLine()?.toInt() } catch (e: NumberFormatException) { println("Invalid input format.") }