I think this question is somewhat related to Kotlin function declaration: equals sign before curly braces
In Scala, every statement is an expression (possibly with Unit
type). If we surround multiple expressions with braces, then the final expression is the actual value of the curly braced part. Therefore,
// Scala
val a = {
val b = 1
val c = b + b
c + c
}
println(a)
The type of a
is Int
and the code prints the value 4
.
However, in Kotlin, this is somewhat different. If we do the same thing in the Kotlin,
// Kotlin
val a = {
val b = 1
val c = b + b
c + c
}
println(a)
The type of a
is () -> Int
and the code prints the Function0<java.lang.Integer>
, which means a 0-ary function object with result type Int
.
So if we want to print the value 4
, we need to do println(a())
.
In fact, the expression {}
in Kotlin is a function () -> ()
.
I cannot find an explanation about this in Kotlin official reference pages. Without a parameter list or ->
, curly braces make a function?
When I use Scala, I write many codes like the first code. However, in Kotlin, it creates a function object and we have to call the function, which may be an overhead in a loop or recursion.
Is there any document about this thing: just curly braces make a function object?
Any way to workaround the overhead in the second code if it is used many times?
EDIT
Here is the actual code that iterates many times:
in Java
while ((count = input.read(data, 0, BYTE_BLOCK_SIZE)) != -1) {
....
}
in Scala
while {
count = input.read(data, 0, BYTE_BLOCK_SIZE)
count != -1
} {
....
}
in Kotlin
while ({
count = input.read(data, 0, BYTE_BLOCK_SIZE)
count != -1
}()) {
...
}
You can see, only Kotlin makes a lot of function objects and calls them.
while
code does not seem to be idiomatic for reading. Wouldn't it better to use (buffered) streams for that? – Tegument