Printing to the console
There are two main ways to print output to the console in Kotlin:
print("Hello")
println("Hello")
Formatting output
You can format output in Kotlin using string templates. String templates are enclosed in backticks (`) and allow you to embed expressions directly into the string. For example, the following code will print "Hello, John Doe!" to the console:
val name = "John Doe"
println("Hello, $name!")
You can also use string interpolation to format numeric values. For example, the following code will print "The square of 5 is 25" to the console:
val number = 5
println("The square of $number is ${number * number}")
Reading input from the console
You can read input from the console in Kotlin using the readLine() function. The readLine() function takes no arguments and returns the next line of text entered by the user. For example, the following code will read a name from the console and then print a greeting message:
val name = readLine()
println("Hello, $name!")
Working with files
You can work with files in Kotlin using the File class. The File class provides methods for reading and writing files. For example, the following code will read the contents of a file named "myfile.txt" and print it to the console:
val file = File("myfile.txt")
val contents = file.readText()
println(contents)
Error handling
Kotlin has a built-in exception handling mechanism. Exceptions are errors that occur during program execution. You can handle exceptions using the try-catch block. The try block contains the code that you want to execute, and the catch block contains the code that you want to execute if an exception occurs. For example, the following code will attempt to read a file named "myfile.txt". If the file does not exist, an exception will be thrown and the catch block will be executed:
try {
val file = File("myfile.txt")
val contents = file.readText()
println(contents)
} catch (e: Exception) {
println("Error reading file: ${e.message}")
}