Hi all - I'm working through the JetBrains Academy...
# getting-started
c
Hi all - I'm working through the JetBrains Academy course on Kotlin and I have a dumb question. I'm at the early point of looking at the output of
Copy code
val result = println("text")
println(result)

text
kotlin.Unit
One of the practice questions asks about the Magic Of
println
and it implies that the value of
result
is
Unit
. While that's true, what's "text" doing in the output? Maybe this is something that I don't need to be worried about (and I'm not) but I'm curious why. println is called twice, once for "text", and then a second time for
println
itself, and the type value of the
println
function is
kotlin.Unit
? Is that true for all functions? Just
println
? Thanks for any clarity you're willing to share!
v
Are you familiar with other languages? Java for example?
j
Correct,
println()
is called twice here. The first time it prints
text
and the second time it prints the value of the
result
variable, which happens to be
Unit
(aka
kotlin.Unit
in its fully-qualified name). The fact that it prints something is a side-effect of calling the function.
Is that true for all functions? Just
println
?
In Kotlin, functions can return values of many types. The return type of the function is declared when declaring the function. Any function that returns "nothing interesting" usually omits the return type and automatically returns the value
Unit
, which is of type
Unit
(the type with only one value).
println
is one such function. Some functions do return more interesting types, for instance:
Copy code
fun myCustomSum(a: Int, b: Int): Int {
    return a + b
}
This is a custom function that returns the sum of its 2 arguments
a
and
b
. If you were to print the result of this function, you would not get `kotlin.Unit`:
Copy code
val result = myCustomSum(3, 5)
println(result) // prints 8
c
Hi @Vampire not with degree of proficiency. I'm pretty inexperienced.
v
I didn't ask for the degree, just whether you are. For example, if you know what a
void
method is in Java, then you know what a
Unit
method in Kotlin is
c
@Joffrey thanks for that response. That helps clarify things, I think!
@Vampire fair point. I don't know about the
void
method in Java.
j
It might not have been very clear from my first message, but in most programming languages, functions can do 2 types of things: • return a value • perform side-effects (do stuff themselves, like a network call, writing to a file, printing to the screen etc.)
println
is a function that has the side-effect of printing to the console a text representation of the value you pass to it. Not all functions have side effects, though (the ones without side-effect are called "pure functions"). However, all functions in Kotlin have a return type, so they return values (when completing successfully). If a function has nothing interesting to return, it will just return
Unit
.
👍 2