Home > other >  Why can private fun shouldRandomlyFail(): Boolean = requestCount % 5 == 0 return different result?
Why can private fun shouldRandomlyFail(): Boolean = requestCount % 5 == 0 return different result?

Time:10-16

The Code A is from offical sample code here.

1: What does requestCount mean? Normally I use requestCount .

2: I comprehend that the author use the fun shouldRandomlyFail() to simulate a real network, the author think that it returns True sometimes and it returns False sometimes.
But I don't think the fun shouldRandomlyFail() will work as the author expected, you know that requestCount is locale variable and never save data, so fun shouldRandomlyFail() will return fixed value. Am I right?

Code 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
}

CodePudding user response:

can be used as a pre-increment or post-increment operator (same for --). variable is the pre-increment form, where variable will be incremented and then the value returned, while variable is the post increment form, the effect is that the original value of variable is returned and then he value is incremented (this is conceptually what happens). You can find more info here : Increment and Decrement Operators

For your second question, requestCount is not a local variable, it is a class member, so the variable scope is to the instance of the class, which lives beyond the scope of the method call on the instance.

  • Related