Console Output
You have already seen examples of using println() and print() for
console output in Kotlin. These functions both take a single argument, and
that argument can be of any type. If the argument is not itself a string,
a string representation of it will be generated, and this will then be
printed.
If you require more complicated output, combining fixed text with values generated by your program, you can achieve this using
- String interpolation
- The
format()extension function of theStringclass - The
printf()method of the objectSystem.out
Printing With String Interpolation
Strings in Kotlin can act as templates, into which the values of program variables will be inserted, in a process known as interpolation.
Python has an equivalent feature, commonly known as the ‘f-string’.
C has no direct equivalent, but the same result can be achieved using the
sscanf() function.
In Kotlin, you can interpolate a variable’s value into a string by including
that variable’s name in your string, prefixed by a $ symbol.
You can also interpolate the results of expressions, property access,
function calls or method calls into a string. In these cases, you need to
enclose the expression, property access or call in braces, as well as using
the $ prefix.
Here are some examples of printing interpolated strings, with the equivalent Python f-string syntax for comparison:
print("Enter your name: ")
val name = readln()
println("Hello $name!")
println("Your name contains ${name.length} characters")
println("Is it a short name? ${name.length < 5}")
println("Uppercase name is ${name.uppercase()}")
name = input("Enter your name: ")
print(f"Hello {name}!")
print(f"Your name contains {len(name)} characters")
print(f"Is it a short name? {len(name) < 5}")
print(f"Uppercase name is {name.upper()}")
Formatted Output
Python f-strings allow you to control the format of the interpolated value
in various ways. For example, you can interpolate a float value with
a specified number of decimal places.
String interpolation in Kotlin is much more basic than that. You’ll need to follow a different approach if you want more control over formatting.
One approach is to use the format() extension function of the String
class. For example, if you have a Float or Double variable named
distance, representing a distance in kilometres, you could format its value
into a string and then print that string with code like this:
println("Distance = %.2f km".format(distance))
Here, %.2f is a format specifier indicating that a floating-point
value should be inserted into the string at this point, and that it should
be formatted using two decimal places. The available format specifiers
are very similar to those used in C.
Another approach is to use the method System.out.printf(). Here’s an
example, with the equivalent C code provided for comparison:
val area = Math.PI * radius * radius
System.out.printf("Circle area is %.3f\n", area)
float area = M_PI * radius * radius;
printf("Circle area is %.3f\n", area);
If you already know C, the nice thing about System.out.printf() is that it
allows you to carry on using a very familiar approach to outputting formatted
data on the console. However, using that System.out prefix repeatedly
is tedious and adds clutter to the source code.
Fortunately, Kotlin provides a solution to this, via the with()
scope function:
with(System.out) {
printf("Circle colour = (%d,%d,%d)\n", r, g, b)
printf("Circumference = %.3f\n", 2.0 * Math.PI * radius)
printf("Area = %.3f\n", Math.PI * radius * radius)
}
Inside the braces, method calls are implicitly made on the subject of the
with call1—in this case, the object System.out, which represents
the standard output stream.
When you use System.out.printf(), you are bypassing Kotlin!
This method is part of the Java standard library. The clever thing about Kotlin is that it integrates seamlessly with Java, allowing you to use anything from the Java standard library, or third-party Java libraries, in your Kotlin programs.
Obviously, this is only true of software that is running on the JVM. If you target a different platform with the compiler then you won’t be able to use things like this in your code.
-
Although it might not look like it, this really is a function call! We will discuss this unusual syntax when we cover functions later. ↩