Kotlin Tutorial 4 — Handling Input And Output
In this tutorial we will be looking closely at intercepting input and generating output as part of basic user interaction with a program. Also the important topic of error handling will be covered.
Input
Kotlin comes with a handy built in function called readLine (part of standard library) to intercept keyboard input from the console. Try the following in the Kotlin REPL:
Output
String templates is supported in Kotlin for both ordinary and raw strings. Python started supporting string interpolation (string templates) from version 3.6 onwards. Try the following in the Kotlin REPL to get an idea of how string templates work:
Kotlin doesn’t have built in string formatting however it has the format function which behaves like Python’s old string formatting style. Try the following in the Kotlin REPL:
Bringing It Together
In Kotlin there are 2 types of errors, compile time and runtime. Compile time errors are caused by the compiler finding errors in the source file(s) when they are being compiled to create a program. Runtime errors are exceptions that are thrown while a program is running (just like Python). All exceptions in Kotlin are treated as unchecked exceptions. They don’t need to be handled at all while the program is running unless there is a real need to do so. Try the following in the Kotlin REPL:
Conclusion
You now know how to handle basic input and output in a program, and dealing with errors when they occur. Next tutorial looks at more complex data types in Kotlin Tutorial 5 — Basic Collections.
TOC
- Kotlin Tutorial 1 — Introduction
- Kotlin Tutorial 2 — Basic Data Types
- Kotlin Tutorial 3 — Basic Operators
- Kotlin Tutorial 4 — Handling Input And Output
- Kotlin Tutorial 5 — Basic Collections
- Kotlin Tutorial 6 — Control Flow
- Kotlin Tutorial 7 — Functions
- Kotlin Tutorial 8 — Modularity
- Kotlin Tutorial 9 — Using An IDE
- Kotlin Tutorial 10 — Classes
- Kotlin Tutorial 11 — Inheritance
- Kotlin Tutorial 12 — Encapsulation And Polymorphism
- Kotlin Tutorial 13 — Generics