df
11/11/2020, 11:28 PMwhile (value.links.next != null) {
any chance to smartcast value.links.next to non-null inside the loop? Basically looking for a counterpart to nullable?.let { it is not null }
Rajkumar Singh
11/11/2020, 11:36 PMdf
11/11/2020, 11:39 PMdf
11/11/2020, 11:40 PMwhile (value.links.next != null) {
doSomething(value);
value = getNextPage(value.links.next)
}
that's more or less the code I have at handRajkumar Singh
11/11/2020, 11:43 PMRajkumar Singh
11/11/2020, 11:44 PMnext
could be null?Vampire
11/11/2020, 11:50 PMvalue
is mutable, so nothing can be smart-casted as a different thread could modify it in the meantime.Nir
11/11/2020, 11:51 PMgenerateSequence
?Nir
11/11/2020, 11:55 PMfor ((value, next) in generateSequence { if (value.links.next != null) value to next else null }) { ... }
Nir
11/11/2020, 11:55 PMforEach
instead of a for loopnanodeath
11/11/2020, 11:57 PMdf
11/12/2020, 12:13 AMdf
11/12/2020, 12:13 AMdf
11/12/2020, 12:15 AMNir
11/12/2020, 12:51 AMvar firstRequest = true
generateSequence("/api/rest/v1/products") {
val response = httpClient.get<ResultPage<Product>> {
url(it)
header("Authorization", "Bearer ${token.accessToken}")
if (firstRequest) {
contentType(ContentType.Application.Json)
parameter("search", objectMapper.writeValueAsString(search))
params.forEach { k, v -> parameter(k, v) }
firstRequest = false
}
}
send(response)
response.links.next?.href
}.takeWhile { true }
Nir
11/12/2020, 12:51 AMtakeAll
insteadgildor
11/12/2020, 8:53 AMwhile (true) {
val value = value.links.next ?: break
doSomething(value)
}
It makes value immutable, smart cast works as expected, it very flexible
One may doesn't like while(true)
estetically, but on practice I don't see big issue there, especially because it provides many benefits
Actual implementation may be different, depending on scope, but it just general idiom, use while(true) + elvis with break to make smart cast work