CanOfBees
05/23/2022, 5:26 PMval 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!Vampire
05/23/2022, 5:30 PMJoffrey
05/23/2022, 5:32 PMprintln()
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? JustIn 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?println
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:
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`:
val result = myCustomSum(3, 5)
println(result) // prints 8
CanOfBees
05/23/2022, 5:32 PMVampire
05/23/2022, 5:36 PMvoid
method is in Java, then you know what a Unit
method in Kotlin isCanOfBees
05/23/2022, 5:39 PMvoid
method in Java.Joffrey
05/23/2022, 5:39 PMprintln
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
.