␡
- 2.1 Conditional Expressions
- 2.2 Statement Termination
- 2.3 Block Expressions and Assignments
- 2.4 Input and Output
- 2.5 Loops
- 2.6 Advanced for Loops and for Comprehensions
- 2.7 Functions
- 2.8 Default and Named Arguments L1
- 2.9 Variable Arguments L1
- 2.10 Procedures
- 2.11 Lazy Values L1
- 2.12 Exceptions
- Exercises
This chapter is from the book
2.4 Input and Output
To print a value, use the print or println function. The latter adds a newline character after the printout. For example,
print("Answer: ") println(42)
yields the same output as
println("Answer: " + 42)
There is also a printf function with a C-style format string:
printf("Hello, %s! You are %d years old.\n", "Fred", 42)
You can read a line of input from the console with the readLine function. To read a numeric, Boolean, or character value, use readInt, readDouble, readByte, readShort, readLong, readFloat, readBoolean, or readChar. The readLine method, but not the other ones, takes a prompt string:
val name = readLine("Your name: ") print("Your age: ") val age = readInt() printf("Hello, %s! Next year, you will be %d.\n", name, age + 1)