Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin Standard Input/Output

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.

1. Standard Output

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!")
    

2. String Templates

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

3. Standard Input

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()!!

4. Reading Specific Data Types

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() }
    

5. Error Handling

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!")
}

Conclusion

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.

  1. Reading from standard input in Kotlin:

    • Use the readLine() function to read a line of text from the standard input.
    val input = readLine()
    
  2. Using readLine() for user input in Kotlin:

    • Prompt the user for input using readLine() and display the result.
    print("Enter your name: ")
    val name = readLine()
    println("Hello, $name!")
    
  3. Parsing input values from the console in Kotlin:

    • Convert the input string to other data types for processing.
    print("Enter your age: ")
    val age = readLine()?.toIntOrNull() ?: 0
    
  4. Handling standard output in Kotlin:

    • Use println() to output text to the standard output.
    println("Hello, Kotlin!")
    
  5. Printing to the console with println() in Kotlin:

    • Print formatted text to the console using println().
    val variable = "World"
    println("Hello, $variable!")
    
  6. Formatting output in Kotlin:

    • Format output using string templates and formatting functions.
    val pi = 3.14159
    println("The value of pi is %.2f".format(pi))
    
  7. Reading and writing files with Kotlin standard I/O:

    • Use FileReader and FileWriter for file I/O operations.
    val file = File("example.txt")
    val content = file.readText()
    
  8. Scanner class and standard input in Kotlin:

    • Utilize the Scanner class for more complex input parsing.
    val scanner = Scanner(System.`in`)
    val number = scanner.nextInt()
    
  9. BufferedReader and InputStreamReader for input in Kotlin:

    • Improve performance with buffered reading using BufferedReader.
    val reader = BufferedReader(InputStreamReader(System.`in`))
    val line = reader.readLine()
    
  10. PrintWriter and BufferedWriter for output in Kotlin:

    • Enhance output operations with PrintWriter and BufferedWriter.
    val writer = PrintWriter(BufferedWriter(FileWriter("output.txt")))
    writer.println("Hello, file!")
    writer.close()
    
  11. Redirecting standard input/output in Kotlin:

    • Redirect standard input/output streams for testing or automation.
    System.setIn(FileInputStream("input.txt"))
    System.setOut(PrintStream("output.txt"))
    
  12. Console input/output in Kotlin console applications:

    • Interact with the console in console applications.
    console.readLine("Enter your password: ")
    console.writer().println("Password accepted.")
    
  13. Error handling for standard input/output operations in Kotlin:

    • Handle exceptions that may occur during I/O operations.
    try {
        val input = readLine()?.toInt()
    } catch (e: NumberFormatException) {
        println("Invalid input format.")
    }