groostav
01/25/2019, 9:02 AMdo {
val x = true
}
while(x)
works but
do try {
val x = true
}
finally {}
while(x)
does not. Can i log this as a bug? Or an enhancement?gildor
01/25/2019, 9:06 AMdo {
try {
val x = true
} finally {
}
} while (x)
}elizarov
01/25/2019, 9:06 AMwhile and finally shall be written on the same line as closing curly brace.Pavlo Liapota
01/25/2019, 9:20 AMx outside of try block where it is declared. But this is not possible as variable is only visible inside scope where it is declared.
So solution would be to declare variable x outside of try block.
do {
val x: Boolean
try {
x = true
} finally {
}
} while (x)Pavlo Liapota
01/25/2019, 9:27 AMtry an expression if possible:
do {
val x = try {
true
} finally {
false
}
} while (x)groostav
01/25/2019, 10:10 AMdo block, and use them for the conditional expression in the while statement. Its a neat trick. Unlike the smart-casting or type-casting tricks however, this trick is not able to see through inline functions (or similar), because... well because the kotlin compiler team has a finite number of hours to work. Still, it does seem like a limitation more than a design choice.groostav
01/25/2019, 10:16 AMdo {
try {
val x = true;
}
} while(x)
also does not work. The problem is the compilers ability to lift the variable x through the try block. It wont do it.Pavlo Liapota
01/25/2019, 10:18 AMdo-while statement is located in the same scope as statement body, that’s why variable declared in a body can be access in condition expression.
While try, if, lambdas, etc. create new scopes.
Consider example:
if (foo) {
val x = true
} else {
val x = false
}
You don’t expect variable x to be visible outside of if block, right?Pavlo Liapota
01/25/2019, 10:22 AMwhen feature was added exactly because people didn’t want to pollute scope with temporary variable declaration:
val a = func() // a is accessible after when block
when (a) {
// ...
}
when(val a = func()) { // a is not accessible after when block
// ...
}elizarov
01/25/2019, 10:51 AM