Kotlin Tutorial 4 — Handling Input And Output

Nick Apperley
2 min readDec 20, 2016

--

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:

Illustration 1: Try Catch example in Kotlin

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

  1. Kotlin Tutorial 1 — Introduction
  2. Kotlin Tutorial 2 — Basic Data Types
  3. Kotlin Tutorial 3 — Basic Operators
  4. Kotlin Tutorial 4 — Handling Input And Output
  5. Kotlin Tutorial 5 — Basic Collections
  6. Kotlin Tutorial 6 — Control Flow
  7. Kotlin Tutorial 7 — Functions
  8. Kotlin Tutorial 8 — Modularity
  9. Kotlin Tutorial 9 — Using An IDE
  10. Kotlin Tutorial 10 — Classes
  11. Kotlin Tutorial 11 — Inheritance
  12. Kotlin Tutorial 12 — Encapsulation And Polymorphism
  13. Kotlin Tutorial 13 — Generics

--

--

Responses (1)