It is a lot cleaner and expressive. Thanks.
For code that allows it, by having null
as breaking return value, i really prefer generateSequence
- it generates an infinite sequence terminated should nextFunction
return null
.
Code for the reader could be written as:
generateSequence { reader.readLine() }.forEach { println(it) }
The drawback of this solution is however that the code itself is not really speaking.
Should a condition other than === null
be required, takeIf
or takeUnless
could be used:
generateSequence(0) { (it + 2).takeUnless { n -> n > 15 } }.forEach { println(it) }
This right here. I keep running into this issue.
Yup, this is not at all uncommon to me.
Consuming a paginated feed or result set is the repeat offender.
while(true)
+ if/break
works fine and doesn’t take much work, but just feels dirty in a language otherwise so elegant. The condition should be part of the loop statement, dammit.
var + duplicated assignment is even worse.
Sure, you can (sometimes) wrap it as a sequence or something, but it feels so unneccessary for a really quite simple bit of looping logic.
I am firmly in the ‘this should be allowed’ side of the debate.
Here is a use case for you that is very critical for my application:
if( (a=(… some expensive evaluation))>0 && (b=(… some expensive evaluation))>0){
… Do something with ‘a’ and ‘b’
}
For example, the expensive evaluation above is a JPA or SQL query. Notice the nuance: second evaluation wont be executed unless first returned valid value, so executing this upfront would be slower.
Another observation: The solution of using lambda does not property address nullability check.
The code below fails with ‘Variable ‘x’ must be initialized’:
var x:Any?;
{x="hello"}()
println(x.toString());