Getting information out of your program and reading input from the user โ that's how your code actually talks to the world.
println() and print()
println() prints text and moves to a new line. print() stays on the same line.
fun main() {
print("Hello ")
print("from ")
println("Kotlin")
println("This is on a new line")
}
This will output: Hello from Kotlin then This is on a new line underneath.
Reading input with readLine()
readLine() reads whatever the user types as a String. You can then convert it if you need a number.
fun main() {
print("What's your name? ")
val name = readLine()
println("Nice to meet you, $name!")
}
Reading numbers
Since readLine() always returns a String, use toInt() or toDouble() to convert.
fun main() {
print("Enter a number: ")
val input = readLine()
val number = input!!.toInt()
println("Double that is ${number * 2}")
}
The !! tells Kotlin "I know this might be null, but I'm sure it's not." We'll talk more about null safety later.