i want to create a usually/sometimes statement for...
# getting-started
t
i want to create a usually/sometimes statement for use with mock data. currently i have:
Copy code
usually({

}, sometimes {

})
is it possible to get rid of the parens for
usually
somehow, so i just get:
Copy code
usually {

} sometimes {

}
?
a
make
usually
return something and
sometimes
an infix function with the
UsuallyResult
on the left hand side
☝️ 1
t
infix! thanks, will check that out
w
Copy code
fun usually(block: () -> Unit) = block()
    infix fun Unit.sometimes(block: () -> Unit) = block()
    
    @Test
    fun asas() {
        usually {
            
        } sometimes {
            
        }
    }
t
well, that was fast
thanks @wbertan!
👍 1
Copy code
data class UsuallyResult(val usually: () -> Unit) {
    infix fun sometimes(sometimes: () -> Unit) {
        if (Math.random() < 0.8) {
            this.usually();
        } else {
            sometimes();
        }
    }
}

fun usually(usually: () -> Unit) = UsuallyResult(usually)

fun main() {
    usually {
        println("This should usually happen")
    } sometimes {
        println("But, sometimes this happens!")
    }
}
any improvement suggestions, or is this okay?
k
Looks good.
I'm very curious, what is your use case for this? Usually (heh) unit tests are as deterministic as possible, right?
t
usually when i write frontends, i tend to not prioritize error handling highly enough
so i'm going to start writing mocked apis that sometimes fail
to clarify, "having an error page" vs "making it feel okay to get an error" is not the same
i want my mocked APIs to randomly fail so i can get a good understanding for how unexpected errors feel for a user
k
I see.
t
and i'm tired of writing
Math.random
everywhere, so i wanted to wrap it in a neat function