Skip to content

Instantly share code, notes, and snippets.

@harsh183
Last active April 23, 2021 12:53
Show Gist options
  • Save harsh183/dbdf535dda4a3e00f214ffe211fc7a63 to your computer and use it in GitHub Desktop.
Save harsh183/dbdf535dda4a3e00f214ffe211fc7a63 to your computer and use it in GitHub Desktop.
Recreating ruby's n.times operator on Kotlin. This is for fun, in all seriousness use the repeat(n) operator
fun main() {
// normal function
repeat(3) { print("Yay $it ") }
// => Yay 0 Yay 1 Yay 2
2.times { print("Looop ") }
// => Looop Looop
10.times { print("$it ") }
// => 0 1 2 3 4 5 6 7 8 9
}
// Note: times is already defined as multiplication in Kotlin as well,
// I just named it as such to recreate the Ruby syntax
infix fun Int.times(fn: (Int) -> Unit) = repeat(this, fn)
@harsh183
Copy link
Author

It's also trivial to write this without using repeat (that's how I initially approached it).

infix fun Int.times(fn: (Int) -> Unit) {
   var i = 0
   while (i < this) {
       fn(i)
       i++
   }
}

@harsh183
Copy link
Author

harsh183 commented May 8, 2020

MIT License

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment