Reputation: 1800
In C one can use { and } as a scope delimiter.
For example:
int myfunc()
{
int i = 4;
{
int j = 5;
i = i + j;
...
}
...
}
In this example the { and } create a new scope and so the j can't be seen outside of the { and }.
Does Kotlin supports this?
Upvotes: 2
Views: 165
Reputation: 40193
Adding to @zsmb13's answer, you may look into scoping functions (Standard.kt). The idiomatic way of creating a scope in Kotlin would be:
var i = 0
run {
i++
}
println(i)
Upvotes: 5
Reputation: 89548
It doesn't, because this syntax creates a lambda expression (which then isn't assigned to anything, and is never called).
So this code does nothing to the initial value of i
:
var i = 0
{
i++
}
println(i) // 0
You can however assign the lambda to a variable and call it:
var i = 0
val f: () -> Int = {
i++
}
f()
println(i) // 1
Or invoke it immediately in a JavaScript-ish style, which might be frowned upon by some people:
var i = 0
{
i++
}()
println(i) // 1
Upvotes: 4