Andrea Giuliano
08/13/2020, 7:19 PMnanodeath
08/13/2020, 7:29 PMfun limiter(cb: () -> Unit, chance: Float) {
if (Math.random() < chance) cb()
}
Casey Brooks
08/13/2020, 7:30 PMrandom.nextDouble()
and compare to your threshold. Using the same instance of Random over the entire process will ensure you have a uniform distribution
val percentage = 0.1 // 10%
if(Random().nextDouble() <= percentage) { // nextDouble produces a value between 0.0 and 1.0
doAThing()
}
Casey Brooks
08/13/2020, 7:30 PMAndrea Giuliano
08/13/2020, 7:31 PMnanodeath
08/13/2020, 7:32 PMfun <T> limiter(cb: () -> T, chance: Float): T {
return if (Math.random() < chance) cb() else ???
}
nanodeath
08/13/2020, 7:33 PMRandom.nextDouble()
Casey Brooks
08/13/2020, 7:34 PMfun <T: Any> limiter(doAThing: () -> T, percentage: Float, random: Random = Random.Default): T? {
return if(random.nextDouble() >= percentage) doAThing() else null
}
Casey Brooks
08/13/2020, 7:35 PM: Any
so you know if the callback was used or not. A non-null value means it hit the callback, a null value means it did not. But you may want to wrap that in some result type for more semantic meaning, tooAndrea Giuliano
08/13/2020, 7:36 PMnanodeath
08/13/2020, 7:38 PMAndrea Giuliano
08/13/2020, 7:39 PMclass PercentageLimiter {
fun <T: Any> apply(function: () -> T): T {
return function()
}
}
class DoingSomething {
fun doSomething(): String {
return "hello world!"
}
}
PercentageLimiter().apply { return DoingSomething().doSomething() }
it seems I canāt return from applyAndrea Giuliano
08/13/2020, 7:41 PMNir
08/13/2020, 7:41 PMNir
08/13/2020, 7:42 PMNir
08/13/2020, 7:42 PMNir
08/13/2020, 7:43 PMNir
08/13/2020, 7:43 PMAndrea Giuliano
08/13/2020, 7:44 PMNir
08/13/2020, 7:47 PMNir
08/13/2020, 7:48 PMAndrea Giuliano
08/13/2020, 7:48 PMNir
08/13/2020, 7:49 PMinline
on your functions that accept lambdasNir
08/13/2020, 7:49 PMAndrea Giuliano
08/13/2020, 7:49 PMlimiter.apply {
return DoingSomething().doSomething()
}
If I do this, it expects a Unit as return and tells me return type mismatch, given string got Unit šNir
08/13/2020, 7:50 PMapply
is inline, then just imagine that basically the contents of apply are inlined immediately, including the lambda invocationNir
08/13/2020, 7:51 PMNir
08/13/2020, 7:51 PMAndrea Giuliano
08/13/2020, 7:51 PMNir
08/13/2020, 7:51 PMreturn@apply
or something like thatAndrea Giuliano
08/13/2020, 7:52 PMAndrea Giuliano
08/13/2020, 7:52 PMNir
08/13/2020, 7:52 PMAndrea Giuliano
08/13/2020, 7:53 PMNir
08/13/2020, 7:53 PMuse
blockNir
08/13/2020, 7:53 PMuse
is an inline functionNir
08/13/2020, 7:54 PMNir
08/13/2020, 7:54 PMNir
08/13/2020, 7:54 PMmyfile.use {
for (line in myFile) {
if line == "ERROR!" {
return
}
}
}
Nir
08/13/2020, 7:54 PM