为什么 private fun shouldRandomlyFail(): Boolean = ++requestCount % 5 == 0 return 会有不同的结果?
Why can private fun shouldRandomlyFail(): Boolean = ++requestCount % 5 == 0 return different result?
代码A来自官方示例代码here.
1:++requestCount
是什么意思?通常我使用 requestCount++
.
2:我理解作者使用fun shouldRandomlyFail()
来模拟一个真实的网络,作者认为它returns True有时和它returns False 有时。
但我认为 fun shouldRandomlyFail()
不会像作者预期的那样工作,你知道 requestCount
是语言环境变量并且从不保存数据,所以 fun shouldRandomlyFail()
将 return 固定值。我说得对吗?
代码A
class FakePostsRepository : PostsRepository {
override suspend fun getPosts(): Result<List<Post>> {
return withContext(Dispatchers.IO) {
delay(800) // pretend we're on a slow network
if (shouldRandomlyFail()) {
Result.Error(IllegalStateException())
} else {
Result.Success(posts)
}
}
}
private var requestCount = 0
/**
* Randomly fail some loads to simulate a real network.
*
* This will fail deterministically every 5 requests
*/
private fun shouldRandomlyFail(): Boolean = ++requestCount % 5 == 0
}
++
可用作预增量或 post-增量运算符(与 --
相同)。 ++variable
是前置自增形式,其中variable
会先自增再返回值,而variable++
是post自增形式,效果是原值variable
的值被返回,然后他的值增加(这在概念上是发生的事情)。
您可以在此处找到更多信息:Increment and Decrement Operators
对于你的第二个问题,requestCount
不是一个局部变量,它是一个class成员,所以变量范围是class的实例,它超出实例上方法调用的范围。
代码A来自官方示例代码here.
1:++requestCount
是什么意思?通常我使用 requestCount++
.
2:我理解作者使用fun shouldRandomlyFail()
来模拟一个真实的网络,作者认为它returns True有时和它returns False 有时。
但我认为 fun shouldRandomlyFail()
不会像作者预期的那样工作,你知道 requestCount
是语言环境变量并且从不保存数据,所以 fun shouldRandomlyFail()
将 return 固定值。我说得对吗?
代码A
class FakePostsRepository : PostsRepository {
override suspend fun getPosts(): Result<List<Post>> {
return withContext(Dispatchers.IO) {
delay(800) // pretend we're on a slow network
if (shouldRandomlyFail()) {
Result.Error(IllegalStateException())
} else {
Result.Success(posts)
}
}
}
private var requestCount = 0
/**
* Randomly fail some loads to simulate a real network.
*
* This will fail deterministically every 5 requests
*/
private fun shouldRandomlyFail(): Boolean = ++requestCount % 5 == 0
}
++
可用作预增量或 post-增量运算符(与 --
相同)。 ++variable
是前置自增形式,其中variable
会先自增再返回值,而variable++
是post自增形式,效果是原值variable
的值被返回,然后他的值增加(这在概念上是发生的事情)。
您可以在此处找到更多信息:Increment and Decrement Operators
对于你的第二个问题,requestCount
不是一个局部变量,它是一个class成员,所以变量范围是class的实例,它超出实例上方法调用的范围。